我想制作一个包装器 Filer
类来与 fstream
库一起工作。
因此,我想通过我自己的 Filer 类的构造函数传递 fstream
类的实例,这导致了以下代码:
Filer::Filer(fstream fileObject)
{
fileObject this->fileObj;
};
虽然当我编译它时,会抛出一个错误:
1>Filer.cpp(10): error C2143: syntax error : missing ';' before 'this'
当我这样做的时候:
Filer::Filer(fstream fileObject)
{
this->fileObj = fileObject;
};
它抛出此错误,提示无法以这种方式分配 fstream;
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::fstream' (or there is no acceptable conversion)
然后我应该如何让我的构造函数接受类型为 fstream
的对象?
最佳答案
你得到的不是 C++。试试这个:
Filer::Filer(fstream& fileObject)
: fileObj(fileObject)
{
}
它使用“初始化列表”来存储对必须声明为类成员的 fileObject
的引用。并且您必须使用引用,因为流是不可复制的。
关于c++ - 如何通过 C++ 中的构造函数传递类/对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26801536/