我不确定运算符重载是否是我要找的东西,但我需要知道在 C++ 中实现以下目标的最佳方法;
我有一个 Employee 类(为简单起见),它只有一个 ID 号 atm。请假设输入文件有一个 int 数字和后面的一些字符(仅显示 1 行),例如:
1234 查尔斯·哈蒙德
这是到目前为止的代码。我正在尝试使用提取运算符将整数和其他数据从输入文件获取到我的类函数 (SetID);
class Employee
{
int employeeID;
public:
void SetID(int);
}
void Employee::SetID(int empID)
{
employeeID = empID;
}
int main(void)
{
int lineCounter = 4;
Employee emp;
//Create filestream objects and open
ifstream input;
ofstream output;
input.open("input.txt");
output.open("output.txt");
for (int i = 0; i < lineCounter; i++)
{
input >> emp.SetID(input.get()); //illegal? Best way to do this
}
//Close program
output.close();
input.close();
system("pause");
return 0;
}
我只是想从输入文件中获取 ID 并将其存储在类成员“employeeID”中,以便稍后用于计算。
最佳答案
一个选择是重载 >>>
运算符并使其成为您的 Employee 类中的友元函数。
类似于:
istream& operator>>( istream& in, Employee& emp )
{
in >> emp.employeeID;
return in;
}
在您的 Employee 类中:
friend istream& operator>> (istream& in, Employee& emp);
关于类函数的 C++ 提取运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23925866/