【发布时间】: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 个问题:
dataFile是否包含Morse.bin内容?file opened successfully消息出现了,但我只是想确认一下。我想从
Decoder类中逐个字符地读取。我遇到的问题是从Decoder类访问dataFile。我尝试为dataFile创建一个访问器函数,但它不允许我访问它。错误消息是File::dataFile is inaccessible。这是有道理的,因为它是私有的。但是,如果我无法创建会返回dataFile的访问器函数,我如何获取dataFile以便对其进行操作?
【问题讨论】:
-
你可以在 protected 中添加 dataFile 或者你可以将
Decoder定义为 friend class。你有第二个选项,但它通常太傻了 不推荐
标签: c++ inheritance fstream