问题描述
我有一个类员工
#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;
}
我试图重载输入操作符>>但是我收到以下错误
I am trying to overload the input operator >> to read in the employee object but i am getting the following error
我做错了什么?
编辑:我知道如何做
edit: I know how to do it through a friend function , i am now trying to learn how to do it through a member function
推荐答案
您不能。
对于二进制运算符@
对象 A a
和 B b
,语法 a @ b
将调用或 运算符@(A,B)
或形式的成员函数的非成员函数形式为 A :: operator @(B)
。没有其他。
For a binary operator@
and objects A a
and B b
, the syntax a @ b
will call either a non-member function of the form operator@(A,B)
or a member function of the form A::operator@(B)
. Nothing else.
所以要使 std :: cin>> C
工作,它必须是 std :: istream
的成员,但由于您不能修改 std :: istream
您不能实现 operator>>
作为成员函数。
So to make std::cin >> C
work it must be as a member of std::istream
, but since you can't modify std::istream
you can't implement operator>>
as a member function.
(除非你想变得奇怪和非常规,写 C 或
C>> std :: cin
,但如果你这样做,其他程序员会讨厌你混淆和非常规的。不要这样做。)
(Unless you want to be weird and unconventional and write C << std::cin
or C >> std::cin
, but if you do that other programmers will hate you for being confusing and unconventional. Do not do this.)
这篇关于没有匹配的操作符>> in std :: cin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!