文件类别

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个问题:


dataFile是否包含Morse.bin内容?显示file opened successfully消息,但我只是想确定一下。
我想从Decoder类中逐字符读取字符。我遇到的问题是从dataFile类访问Decoder。我尝试为dataFile创建访问器函数,但不允许我访问它。错误消息是File::dataFile is inaccessible。这是有道理的,因为它是私有的。但是,如果我无法创建将返回dataFile的访问器函数,如何获得dataFile的保全以便对其进行操作?

最佳答案

还没。您尚未阅读。
使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";
}

10-04 14:48