这是我的头文件。我试图重载istream操作符并在我的main函数中使用ifstream读取带有结构化数据(行和列)的文本文件。我收到错误“[错误]不匹配'运算符>>' (操作数类型是'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
}
};
答案 0 :(得分:3)
您必须更改get_name()
以返回非const引用,例如string& get_name();
以使其工作/编译。但看起来很奇怪。
您可以做的是直接传递会员name
iss >> employee.name;
friend
做了什么。
请勿忘记返回信息流is
。