我正在用 C++ 程序编写我的第一个大“类”(它处理 I/O 流),我想我理解了对象、方法和属性的概念。 虽然我想我仍然没有获得封装概念的所有权利, 因为我希望我的名为 File 的类具有
- 名称(文件路径),
- 阅读流,以及
- 写入流
作为属性,
也是它的第一个实际获取 File 对象的“写入流”属性的方法...
#include <string>
#include <fstream>
class File {
public:
File(const char path[]) : m_filePath(path) {}; // Constructor
File(std::string path) : m_filePath(path) {}; // Constructor overloaded
~File(); // Destructor
static std::ofstream getOfstream(){ // will get the private parameter std::ofStream of the object File
return m_fileOStream;
};
private:
std::string m_filePath; // const char *m_filePath[]
std::ofstream m_fileOStream;
std::ifstream m_fileIStream;
};
但我收到错误:
Error 4 error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>' c:\program files (x86)\microsoft visual studio 10.0\vc\include\fstream 1116
向 fstream.cc 的以下部分报告我:
private:
_Myfb _Filebuffer; // the file buffer
};
您能帮我解决这个问题并能够使用流作为我的类的参数吗?我尝试返回引用而不是流本身,但我也需要一些帮助(也不起作用......)。 提前致谢
最佳答案
改变
static std::ofstream getOfstream(){ // will get the private parameter std::ofStream of the object File
return m_fileOStream;
};
到
// remove static and make instance method returning a reference
// to avoid the copy constructor call of std::ofstream
std::ostream& getOfstream(){ return m_fileOStream; }
关于c++ - 在其他类中声明的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11636921/