【问题标题】:Why does fstream not utilize the istream prototype of operator>>?为什么 fstream 不使用 operator>> 的 istream 原型?
【发布时间】: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&lt;&lt; 应该通过 const 引用去医院。

标签: c++ iostream fstream


【解决方案1】:

你必须使用:

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

【讨论】:

  • 太棒了!我完全忘记了'->'运算符会自动取消引用它,所以没有它我必须手动取消引用!太感谢了!我有一个时间限制,才能接受你的回答,超过限制后我会回来奖励你积分。再次感谢您!
猜你喜欢
  • 2011-05-08
  • 2018-05-29
  • 2014-02-06
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
相关资源
最近更新 更多