[英]Private member declared in other class
我正在用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,_Traits> :: basic_ios':无法访问在类'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; }
每个班级都有三个部分,所以假设以下班级:
class Example{
public:
void setTime(int time);
int getTime() const;
private:
int time;
protected:
bool ourAttrib;
}
您会看到公共,私有和受保护的单词,是的,它们解释了封装,当您可以将private用于方法或属性时,只有成员可以使用它。但是当您使用public时,任何人都可以使用它。此类,派生类可以使用受保护的和继承的它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.