2016-04-23 131 views
1

File类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 conten TS? file opened successfully消息显示,但我只是想确认。

  2. 我想从Decoder类中按字符读取一个字符。我遇到的问题是从Decoder类访问dataFile。我试图为dataFile创建一个存取函数,但它不允许我访问它。错误消息是File::dataFile is inaccessible。这是有道理的,因为它是私人的。但是,如果我无法创建将返回dataFile的访问函数,那么如何获取dataFile以便操纵它?

+0

您可以添加** **数据文件在受保护的,或者你可以定义'Decoder'为**友元类**,你有第二个选择,但它太傻正常**不推荐** – Pavan

回答

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

'fstream getDataFile(){return dataFile;}'给我一个'dataFile'无法访问的错误。 – Bryan

+0

@Bryan你在'Decoder'类中添加了那个吗?如果是这样,你需要把它放在'File'类中。私人成员只能在宣称的班级中进行访问。甚至没有继承类可以访问它。 –

+0

我将它添加到文件的公共部分 – Bryan