为什么fstream不使用运算符的istream原型>>?

Jar*_*nce 5 c++ fstream iostream

我有一个类使用友元函数来重载运算符>>.重载的操作符方法在标准cin使用上测试良好.但是,当我尝试升级代码以使用ifstream对象而不是istream对象时,原型不会被识别为有效方法.

我理解ifstream是从istream继承的,因此,多态应该允许ifstream对象与istream重载函数一起运行.我的理解有什么问题?

是否有必要为每个输入流类型复制函数?

类:

#include <iostream>
#include <cstdlib> 
#include <fstream>

using namespace std;

class Hospital {
public:
    Hospital(std::string name);
    std::string getName();
    void write();
    friend ostream & operator<<( ostream &os, Hospital &hospital );
    friend istream & operator>>( istream &is, Hospital &hospital );
private:
    void readFromFile( std::string filename );
    std::string m_name;
};
Run Code Online (Sandbox Code Playgroud)

功能实现:

istream &operator>>( istream &is, Hospital &hospital ){
    getline( is, hospital.m_name );
    return is;
}
Run Code Online (Sandbox Code Playgroud)

错误:

Hospital.cpp:在成员函数'void Hospital :: readFromFile(std :: string)':Hospital.cpp:42:24:错误:不匹配'operator >>'(操作数类型是'std :: ifstream {aka std :: basic_ifstream}'和'Hospital*')storedDataFile >> this;

调用readFromFile后,堆栈中会出现此错误,为了完整性,我将其复制到此处:

/**
 * A loader method that checks to see if a file exists for the given file name.
 * If no file exists, it exits without error. If a file exists, it is loaded
 * and fills the object with the contained data. WARNING: This method will overwrite
 * all pre-existing and preset values, so make changes to the class only after
 * invoking this method. Use the write() class method to write the data to a file.
 * @param filename
 */
void Hospital::readFromFile(std::string filename) {
    ifstream storedDataFile( filename.c_str() );
    if( storedDataFile ){
        storedDataFile >> this;
        storedDataFile.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,'this'是一个Hospital对象.

所有的帮助和想法都表示赞赏.我正在重新学习C++并寻求对语言及其过程的更深入理解.

P0W*_*P0W 8

你必须使用:

storedDataFile >> *this;
               // ~~ dereference the `this` pointer (i.e. Hostipal Object)
              /* Enabling the match for operator>>( istream &is, Hospital &hospital ) */
Run Code Online (Sandbox Code Playgroud)