在其他类中声明的私有成员

时间:2012-07-24 18:18:51

标签: c++ class attributes stream private

我在c ++程序中编写我的第一个大“类”(它处理I / O流),我想我理解了对象,方法和属性的概念。 虽然我想我仍然没有获得封装概念的所有权利, 因为我希望我的班级名为File

  • 名称(文件的路径),
  • 阅读流,
  • 写作流

作为属性,

也是第一个实际获取File对象的“write stream”属性的方法......

#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&lt; _Elem,_Traits&gt; :: basic_ios':   无法访问类中声明的私有成员   '的std :: basic_ios&LT; _Elem,_Traits&GT;' c:\ program files(x86)\ microsoft   visual studio 10.0 \ vc \ include \ fstream 1116

向我报告fstream.cc的以下部分:

private:
    _Myfb _Filebuffer;  // the file buffer
    };

然后你可以帮我解决这个问题,并且可以使用流作为我班级的参数吗?我试图返回一个引用而不是流本身,但我也需要一些帮助(不起作用......)。 提前致谢

2 个答案:

答案 0 :(得分:4)

变化

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; }

答案 1 :(得分:1)

每个类有三个部分,所以假设以下类:

class Example{

public:
   void setTime(int time);
   int getTime() const;
private:
 int time;
protected:
bool ourAttrib;

}

你看到公共,私有和受保护的单词,是的,他们解释封装,当你可以使用私有方法或属性时,只有成员可以使用它。但是当你使用公共时,永远使用它。现在受到保护:当你从这个类派生的类,派生类可以使用protected和inherited它们。

相关问题