no match for operator >> in std::cin

2019-08-25 05:15发布

问题:

I have a class employee

#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

no match for operator >> in std::cin

What am i doing wrong ???

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

回答1:

I know how to do it through a friend function , i am now trying to learn how to do it through a member function

You can't.

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.

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.

(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.)



回答2:

You need to declare it thusly:

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

Implementation:

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

As a side note, it's generally a bad idea to do using namespace std; within a header file.



回答3:

It seems that we cannot declare operator << inside class declaration. I've tried it and it is OK.

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