为什么fstream不利用operator>>的istream原型?

Why does fstream not utilize the istream prototype of operator>>?

我有一个 class,它使用友元函数来重载运算符>>。重载运算符方法在标准 cin 使用上测试得很好。但是,当我尝试将代码升级为使用 ifstream 对象而不是 istream 对象时,原型未被识别为有效方法。

我的理解是ifstream继承自istream,因此,多态性应该允许ifstream对象与istream重载函数一起操作。我的理解有什么问题吗?

是否需要为每种输入流类型复制函数?

Class:

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

函数实现:

istream &operator>>( istream &is, Hospital &hospital ){
    getline( is, hospital.m_name );
    return is;
}

错误:

Hospital.cpp: In member function ‘void Hospital::readFromFile(std::string)’: Hospital.cpp:42:24: error: no match for ‘operator>>’ (operand types are ‘std::ifstream {aka std::basic_ifstream}’ and ‘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();
    }
}

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

感谢所有帮助和想法。我正在重新自学 C++ 并寻求对该语言及其过程的更深入理解。

你必须使用:

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