【问题标题】:Fstream access as private memberFstream 作为私有成员访问
【发布时间】:2016-04-23 15:50:20
【问题描述】:

文件类

class File
{
private:
    fstream dataFile;

public:
    File();
};

File::File()
{
    dataFile.open("Morse.bin", ios::in | ios::binary);
    if(dataFile.fail())
        cout << "File could not be opened.\n";
    else
        cout << "File opened successfully!\n";
}

解码器类

class Decoder: public File
{
private:
    char line;

public:
    void getLine();
};

void Decoder::getLine()
{
    while(dataFile.get(line))
    {
       cout << line;
    }
}

2 个问题:

  1. dataFile 是否包含Morse.bin 内容? file opened successfully 消息出现了,但我只是想确认一下。

  2. 我想从Decoder 类中逐个字符地读取。我遇到的问题是从Decoder 类访问dataFile。我尝试为dataFile 创建一个访问器函数,但它不允许我访问它。错误消息是File::dataFile is inaccessible。这是有道理的,因为它是私有的。但是,如果我无法创建会返回 dataFile 的访问器函数,我如何获取 dataFile 以便对其进行操作?

【问题讨论】:

  • 你可以在 protected 中添加 dataFile 或者你可以将Decoder 定义为 friend class。你有第二个选项,但它通常太傻了 不推荐

标签: c++ inheritance fstream


【解决方案1】:
  1. 还没有。你还没有读过它。
  2. 使dataFile 受保护,或从File 提供对其的访问器。

    class File
    {
    protected:
        fstream dataFile;
    
    public:
        File();
    };
    
    File::File()
    {
        dataFile.open("Morse.bin", ios::in | ios::binary);
        if(dataFile.fail())
            cout << "File could not be opened.\n";
        else
            cout << "File opened successfully!\n";
    }
    

【讨论】:

  • fstream getDataFile() {return dataFile;} 给我一个dataFile 无法访问的错误。
  • @Bryan 你是在Decoder 类中添加的吗?如果是这样,您需要将其放在 File 类中。私有成员只能在声明它的类中访问。甚至继承类也不能访问它。
  • 我将其添加到文件的公共部分
猜你喜欢
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多