我有一个使用友元函数来重载运算符>>的类。重载的操作符方法在标准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;
};
功能实现:
istream &operator>>( istream &is, Hospital &hospital ){
getline( is, hospital.m_name );
return is;
}
错误:
Hospital.cpp:在成员函数'void中 Hospital :: readFromFile(std :: string)':Hospital.cpp:42:24:错误:没有 匹配'运算符&gt;&gt;'(操作数类型是'std :: ifstream {aka std :: basic_ifstream}'和'Hospital *') storedDataFile&gt;&gt;这;
调用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();
}
}
在这种情况下,&#39;这个&#39;是医院的对象。
感谢所有帮助和想法。我正在重新学习C ++并寻求对语言及其过程的更深入理解。
答案 0 :(得分:8)
你必须使用:
storedDataFile >> *this;
// ~~ dereference the `this` pointer (i.e. Hostipal Object)
/* Enabling the match for operator>>( istream &is, Hospital &hospital ) */