2012-07-24 81 views
2

我在C++程序(它处理I/O流)中编程我的第一个大“类”,我想我理解了对象,方法和属性的概念。 虽然我想我还没有得到封装概念的所有权利, 因为我希望我的类名为文件有在其他类中声明的私有成员

  • 名称(文件的路径),
  • 读取流和
  • 书写流

的属性,

也是它的第一种方法实际得到的的“写流”属性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 
    }; 

你能不能再帮我解决这和能够使用流作为我的课的参数吗?我试图返回一个引用而不是流本身,但是我也需要一些帮助(也不管用......)。 在此先感谢

+0

您应该在您尝试从静态成员函数访问实例成员的事实中出现错误。当你把它称为'File :: getOfstream()'时会发生什么? – chris 2012-07-24 18:20:29

+2

也许你应该考虑将*引用*返回给std :: ofstream而不是副本? – Roddy 2012-07-24 18:21:30

+0

这真的是第一个错误信息吗?我会期待一些(可能是隐含的)复制构造函数。 – aschepler 2012-07-24 18:21:45

回答

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

谢谢,现在我想怎么称它为函数参数?我总是得到这个错误: 类型“std :: ofstream&”(不是const限定)的引用不能被 初始化为类型“std :: ostream”的值 – 2012-07-25 21:05:25

+0

将返回参数更改为std :: ofstream: std :: ofstream&getOfstream(){return m_fileOStream; } – mohaps 2012-07-25 21:35:35

+0

仍然没有...我使用它的方法: _INT文件:: sendErrorOpeningStream(的std :: string ifstream_ofstream,**的std :: ofstream的OUTPUTFILE **,字符* WD)_ --- 我再拿出: _error C2664:'File :: sendErrorOpeningStream':无法将参数2从'std :: ostream'转换为'std :: ofstream'_ – 2012-07-26 15:10:27

1

每一类有三个部分,因此,假设下面的类:

class Example{ 

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

} 

你看公共,私有和保护的话,是的,他们解释封装,当你可以使用私有的方法或属性,只有成员可以使用它。但是当你使用public时,任何人都可以使用它。现在受保护:当你从这个类派生类时,派生类可以使用受保护并继承它们。

+0

如果我有“public”,“private”,“protected”,然后再次“public” ,是的 - 我现在有四个部分,是吗? – 2012-07-25 00:55:00

+0

哦不,你应该3节:pubclic,私人,受保护 – 2012-07-25 05:14:24

相关问题