【问题标题】:Private member declared in other class在其他类中声明的私有成员
【发布时间】: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


【解决方案1】:

改变

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

【讨论】:

  • 谢谢,现在我应该如何将其称为函数参数?我总是收到此错误:“std::ofstream &”类型的引用(非 const 限定)无法使用“std::ostream”类型的值进行初始化
  • 将返回参数更改为 std::ofstream: std::ofstream& getOfstream(){ return m_fileOStream; }
  • 还是不行...我在方法中使用它:int File::sendErrorOpeningStream(std::string ifstream_ofstream, std::ofstream outputFile, char * wd) --- 然后我想出:error C2664: 'File::sendErrorOpeningStream' : cannot convert parameter 2 from 'std::ostream' to 'std::ofstream'
【解决方案2】:

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

class Example{

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

}

你看到 public、private 和 protected 的话,是的,它们解释了封装,当你可以对方法或属性使用 private 时,只有成员可以使用它。但是当你使用 public 时,每个人都可以使用它。现在受保护:当你类派生自这个类,派生类可以使用protected和继承它们。

【讨论】:

  • 我有“public”、“private”、“protected”然后又是“public”怎么样,是的——我现在有四个部分,是吗?
  • 哦不,你应该 3 个部分:公共、私有、受保护
猜你喜欢
  • 1970-01-01
  • 2011-02-24
  • 2014-08-25
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2017-04-20
相关资源
最近更新 更多