【发布时间】:2015-12-03 11:28:08
【问题描述】:
我有一个类使用友元函数来重载运算符>>。重载的运算符方法在标准 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:错误:否 匹配‘operator>>’(操作数类型是‘std::ifstream {aka std::basic_ifstream}”和“医院*”) 存储数据文件>>这个;
调用 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++,并寻求更深入地了解该语言及其过程。
【问题讨论】:
-
this是一个指针Hospital对象。 -
通过 const 引用获取名称,如果它只是一个类成员,您也可以通过 const 引用从
getName返回名称。operator<<应该通过 const 引用去医院。