【问题标题】:Operator Overloading Error: no match for 'operator>>'运算符重载错误:“运算符>>”不匹配
【发布时间】:2018-07-19 12:43:41
【问题描述】:

这是我的头文件。我试图重载 istream 运算符并在我的主函数中使用 ifstream 来读取具有结构化数据(行和列)的文本文件。我收到错误“[Error] no match for 'operator>>'(操作数类型是 'std::istringstream {aka std::basic_istringstream}' 和 'std::string {aka std::basic_string}') 我评论了我得到错误的地方。 到目前为止,我的主要功能除了类和对象之外基本上是空的。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string> 
using namespace std;

class Record
{
    private:
        string name;
        int id;
        double rate;
        double hours;
    public: 
        Record();
        Record (string n, int empid, double hourlyRate, double hoursWorked); 
// constructor

        void read_data_from_file();
        double calculate_wage();
        void print_data();

        /* SETTERS AND GETTERS */           
        void set_name (string n);
        string get_name();

        void set_id (int empid);
        int get_id();

        void set_rate (double hourlyRate);
        double get_rate();

        void set_hoursWorked(double hoursWorked);
        double get_hoursWorked();
        /* END OF SETTERS AND GETTERS */

        friend istream& operator >> (istream& is, Record& employee)
        {
            string line;
            getline (is, line);

            istringstream iss(line);

            iss >> employee.get_name(); // where i get error
        }

}; 

【问题讨论】:

  • 您必须更改 get_name() 以返回非常量引用,例如 string&amp; get_name(); 以使其工作/编译。但是会显得很奇怪。但是你可以直接传递name 成员 -- iss &gt;&gt; employee.name 你为此设置了 fraind
  • 为什么是istringstream getline(is, employee.name); 不工作吗?还是您有更多想法?

标签: c++ class object compiler-errors operand


【解决方案1】:

您必须更改 get_name() 以返回非常量引用,例如 string&amp; get_name(); 以使其工作/编译。但会看起来很奇怪。

你可以做的是直接传递成员name

iss >> employee.name;

friends 就是这样做的。

并且不要忘记返回流is

【讨论】:

  • 加一提return
猜你喜欢
  • 2012-07-23
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-18
相关资源
最近更新 更多