与 std::cin 中的运算符>>不匹配

no match for operator >> in std::cin

本文关键字:gt 不匹配 运算符 std cin      更新时间:2023-10-16

我有一个班级员工

#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;
}

我试图重载输入运算符>>以读取员工对象,但我得到了以下错误

std::cin 中的运算符>>不匹配

我做错了什么???

edit:我知道如何通过朋友函数来完成,我现在正试图通过成员函数来学习如何完成

我知道如何通过朋友功能来完成,我现在正试图通过成员功能来学习如何完成

你不能。

对于二进制operator@以及对象A aB b,语法a @ b将调用形式operator@(A,B)的非成员函数或形式A::operator@(B)的成员函数。没有别的。

因此,要使std::cin >> C工作,它必须是std::istream的成员,但由于不能修改std::istream,因此不能将operator>>实现为成员函数。

(除非你想变得怪异和非传统,写C << std::cinC >> std::cin,但如果你这样做,其他程序员会讨厌你混淆和非传统。不要这样做。)

您需要这样声明:

class employee
{
public:
    friend std::istream& operator >> (std::istream& is, employee& employee);
}; // eo class employee

实施:

std::istream& employee::operator >> (std::istream& is, employee& employee)
{
    is >> employee.salary; // this function is a friend, private members are visible.
    return is;
};

附带说明一下,在头文件中执行using namespace std;通常是个坏主意。

似乎我们不能声明运算符<lt;内部类声明。我试过了,还可以。

#include <stdio.h>
#include <iostream>
using namespace std;
struct foo {
    int field;
};
istream& operator >> (istream& cin, foo& a){
    cin >> a.field;
    return cin;
}
foo a;
main(){
    cin >> a;
}