不匹配运营商>>在std :: cin

时间:2013-11-26 13:34:00

标签: c++ debugging operator-overloading

我有一名班级员工

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

}

我正在尝试重载输入运算符&gt;&gt;读取员工对象,但我收到以下错误

  

不匹配运营商&gt;&gt;在std :: cin

我做错了什么???

编辑:我知道如何通过朋友功能来实现,我现在正在尝试通过成员函数学习如何做到这一点

3 个答案:

答案 0 :(得分:2)

你需要这样声明:

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

作为旁注,在标题文件中通常bad ideausing namespace std;

答案 1 :(得分:2)

  

我知道如何通过朋友功能来实现,我现在正在尝试通过成员函数学习如何实现

你不能。

对于二进制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,但如果你这样做,其他程序员会讨厌你混淆和非传统。不要这样做。)

答案 2 :(得分:0)

似乎我们无法声明运营商&lt;&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;
}
相关问题