【发布时间】:2012-07-24 18:18:50
【问题描述】:
我正在用 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;
};
但我得到了错误:
错误 4 错误 C2248: 'std::basic_ios<_elem>::basic_ios' : 无法访问在类中声明的私有成员 'std::basic_ios<_elem>' c:\program files (x86)\microsoft 视觉工作室 10.0\vc\include\fstream 1116
向 fstream.cc 的以下部分报告我:
private:
_Myfb _Filebuffer; // the file buffer
};
然后你能帮我解决这个问题并能够使用流作为我班级的参数吗?我试图返回一个引用而不是流本身,但我也需要一些帮助(也不起作用......)。 提前致谢
【问题讨论】:
-
您应该在尝试从静态成员函数访问实例成员时遇到错误。当您将其称为
File::getOfstream()时会发生什么? -
也许您应该考虑将 reference 返回到 std::ofstream 而不是副本?
-
这真的是第一条错误信息吗?我会期待一个(可能是隐式的)复制构造函数。
-
与您的错误无关:您不需要 2 个构造函数重载,只有采用
std::string的一个就足够了,因为std::string有一个采用const char *的非explicit构造函数.因此,如果您使用const char *参数调用 File 构造函数,编译器将执行到std::string的隐式转换 -
确实,做出了改变。非常感谢!
标签: c++ class attributes stream private