問題描述
C++返回一個帶有私有構造函數的類實例 (C++ return a class instance with private constructor)
嘿,我的課程有問題。它應該有一個返回相同類但具有其他私有構造函數的方法。但它因特定錯誤而失敗:
error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' :
cannot access private member declared in class '
這是頭文件:
class XMLClass {
private:
bool isGood();
std::vector<std::string> xmlRowList;
std::fstream xmlFS;
XMLClass(std::string newList);
public:
XMLClass(char *filename,std::string root);
std::string getAttribute(char *att);
std::string getText(void);
XMLClass getChildNode(std::string childNode);
};
這是導致錯誤的方法:
XMLClass XMLClass::getChildNode(std::string Node)
{
XMLClass newXML(Node);
return newXML;
}
## 參考解法 #### 方法 1:
The problem is fstream
class member ‑ streams are non‑copyable and as a consequence, so is your class.
To return an object from function by value, you need a copy constructor. But you don't have one because default generated one would be ill‑formed.
If you've got C++11 support, you can implement move constructor for your class. If not, you'll need to store a pointer to the stream.
方法 2:
Someone will probably write a more detailed answer, but I Think problem is This:
std::fstream xmlFS;
You can't copy it, which is needed for this return by value:
return newXML;
Solution should be to write copy constructor and assignment operator for your class, which handle this member variable correctly.
Check out C++ Rule of Three while you are at it.
(by Eddy Haselhoff、jrok、hyde)