Fstream作为私人会员访问

时间:2016-04-23 15:50:21

标签: c++ inheritance fstream

文件类

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课程中逐字逐句地阅读。我遇到的问题是从dataFile课程访问Decoder。我尝试为dataFile创建一个访问器函数,但它不允许我访问它。错误消息是File::dataFile is inaccessible。这是有道理的,因为它是私人的。但是,如果我无法创建一个将返回dataFile的访问者函数,那么如何操纵dataFile才能操纵它?

1 个答案:

答案 0 :(得分:0)

  1. 尚未。你没有读过它。
  2. 使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"; } 为其提供访问权限。

    Na123