运算符重载错误:与"operator>>"不匹配 [英] Operator Overloading Error: no match for 'operator>>'

查看:53
本文介绍了运算符重载错误:与"operator>>"不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is my header file. Im trying to overload the istream operator and use ifstream in my main function to read in a text file with structured data (rows and columns). I am getting the error "[Error] no match for 'operator>>' (operand types are 'std::istringstream {aka std::basic_istringstream}' and 'std::string {aka std::basic_string}') I commented where I am getting the error. My main function is basically empty so far besides The class and object.

#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&get_name(); 使其正常工作/编译.但是看起来会很奇怪.

You have to change the get_name() to return a non-const reference, like string& get_name(); to get it working/compile. But will look strange.

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

What you can do instead is pass the member name directly

iss >> employee.name;

这就是 friend 的工作.

别忘了返回流 is .

这篇关于运算符重载错误:与"operator&gt;&gt;"不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆