我有类(class)员工
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class employee
{
public:
double operator + (employee);
istream& operator>> (istream&);
employee(int);
double getSalary();
private:
double salary;
};
int main()
{
employee A(400);
employee B(800);
employee C(220);
cin>>C;
}
employee::employee(int salary)
{
this->salary = salary;
}
double employee::operator + (employee e)
{
double total;
total = e.salary + this->salary;
return total;
}
double employee::getSalary()
{
return this->salary;
}
istream& employee::operator>> (istream& in)
{
in>>this->salary;
return in;
}
我试图重载输入运算符 >> 以读取员工对象,但出现以下错误
no match for operator >> in std::cin
我做错了什么???
编辑:我知道如何通过友元函数做到这一点,我现在正在尝试学习如何通过成员函数做到这一点
最佳答案
I know how to do it through a friend function , i am now trying to learn how to do it through a member function
你不能。
对于二进制 operator@
和对象 A a
和 B b
, 语法 a @ b
将调用 或者 形式为 operator@(A,B)
的非成员函数或 A::operator@(B)
形式的成员函数.没有别的。
所以要std::cin >> C
它必须作为 std::istream
的成员工作, 但由于您无法修改 std::istream
你不能实现 operator>>
作为成员函数。
(除非你想变得怪异和标新立异并写成 C << std::cin
或 C >> std::cin
,但如果你这样做,其他程序员会因为你的困惑和标新立异而讨厌你。不要这样做。)
关于c++ - std::cin 中的运算符 >> 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218520/