gpt4 book ai didi

c++ - 运算符重载错误: no match for 'operator>>'

转载 作者:行者123 更新时间:2023-12-02 11:11:54 25 4
gpt4 key购买 nike

这是我的头文件。我试图重载istream运算符并在我的主要功能中使用ifstream来读取具有结构化数据(行和列)的文本文件。我收到错误“[错误]与'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& get_name();才能使其正常工作/编译。但是会看起来很奇怪。

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

iss >> employee.name;

那就是 friend所做的。

并且不要忘记返回流 is

关于c++ - 运算符重载错误: no match for 'operator>>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48694081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com