【发布时间】: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& get_name();以使其工作/编译。但是会显得很奇怪。但是你可以直接传递name成员 --iss >> employee.name你为此设置了fraind。 -
为什么是
istringstream?getline(is, employee.name);不工作吗?还是您有更多想法?
标签: c++ class object compiler-errors operand