c++ - 在其他类中声明的私有(private)成员

标签 c++ class attributes stream private

我正在用 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/

相关文章:

c++ - 为什么 "error: invalid application of ' sizeof' 为使用 unique_ptr 的不完整类型”通过添加空析构函数来修复?

c# - 如何将 MonoBehaviour 添加到 sprite (Player)?

java - 有角度和距离结构或类是个好主意吗

c# - 是否可以将两个 C# 属性合并为一个?

android - C++中类似于Android的ArrayMap的容器

c++ - 如何使用 opencv 从矩阵 vector 构建图像

java - 安卓 : Need to create Shared Preferences object in c++ NDK and Store some Boolean value

VB.NET强类型集合

c# - 自定义属性 - 获取底层枚举的值

html - 输入表单属性可以指定多个表单ID吗?或不?