简体   繁体   English

Fstream作为私人会员访问

[英]Fstream access as private member

File class 文件类

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

Decoder class 解码器类

class Decoder: public File
{
private:
    char line;

public:
    void getLine();
};

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

2 Questions: 2个问题:

  1. Does dataFile contain the Morse.bin contents? dataFile是否包含Morse.bin内容? The file opened successfully message shows up, but I just want to make sure. file opened successfully消息显示,但我只是想确认。

  2. I want to read a character by character from in the Decoder class. 我想在Decoder类中逐个字符地读取字符。 The issue I am having is accessing the dataFile from the Decoder class. 我遇到的问题是从Decoder类访问dataFile I tried creating a accessor function for the dataFile but it won't allow me to access it. 我尝试为dataFile创建一个访问器函数,但它不允许我访问它。 The error messages is that File::dataFile is inaccessible . 错误消息是File::dataFile is inaccessible Which make sense because it is private. 这是有道理的,因为它是私人的。 However, if I can't create a accessor function which would return dataFile , how do I get a hold of dataFile in order the manipulate it? 但是,如果我无法创建一个可以返回dataFile的访问器函数,那么如何操作dataFile呢?

  1. Not yet. 还没。 You haven't read from it. 你没有读过它。
  2. Make dataFile protected, or provide an accessor to it from File . 使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"; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM