Use of overloaded operator '>>' is ambiguous (with operand types 'istream' (aka 'basic_istream<char>') and 'MyIncreEx')

StackOverflow https://stackoverflow.com/questions/13327539

Вопрос

Here is the code and I don't seem to find what's wrong with it; I need to overload the << and >> operators, but I get the following error:

Use of overloaded operator '>>' is ambiguous (with operand types 'istream' (aka 'basic_istream') and 'MyIncreEx')

I can't see what's really ambiguous about it:

#include<iostream>
using namespace std;


class MyIncreEx;
istream& operator>>(istream& is, MyIncreEx& s);
ostream& operator<<(ostream &os, MyIncreEx& s);
MyIncreEx operator++(MyIncreEx& d, int dummy);
MyIncreEx operator++(MyIncreEx& d);

class MyIncreEx
{
friend istream& operator>>(istream& is, MyIncreEx s);
friend ostream& operator<<(ostream& os, MyIncreEx s);
friend MyIncreEx operator++(MyIncreEx& d, int dummy);   //post-fix ex: x++;
friend MyIncreEx operator++(MyIncreEx& d);  //pre-fix ex: ++x;

public:
MyIncreEx(){num1=0; num2=0; num3=0;};

int num1;
int num2;
int num3;
};

//------------------------------------------------
istream& operator>>(istream& is, MyIncreEx& s)
{
is >> s.num1;
is >> s.num2;
is >> s.num3;
return is;
};

//------------------------------------------------
ostream& operator<<(ostream &os, MyIncreEx& s)
{
os << "(" << s.num1 <<"," <<s.num2 << "," << s.num3 <<")"<< endl;
return os;
};

//------------------------------------------------
MyIncreEx operator++(MyIncreEx& d)              //pre-fix   ex: ++x;
{
d.num1=d.num1+1;
d.num2=d.num2+1;
d.num3=d.num3+1;

return d;
};
//------------------------------------------------

MyIncreEx operator++(MyIncreEx& d, int dummy)   //post-fix ex: x++;
{
d.num1=d.num1+1;
d.num2=d.num2+1;
d.num3=d.num3+1;
return d;
};

//------------------------------------------------
int main()
{
MyIncreEx obj;

cout << "please enter three numbers: ";
cin  >> obj;
cout << "The original value are: ";
cout << obj;
cout << endl;
obj++;
cout << "The new values after obj++ are: ";
cout <<  obj;
cout << endl;
++obj;
cout << "The new values after ++obj are: ";
cout << obj;
cout << endl;

}
//------------------------------------------------
Это было полезно?

Решение

You declared two different versions of the output operators:

istream& operator>>(istream& is, MyIncreEx& s);
ostream& operator<<(ostream &os, MyIncreEx& s);

class MyIncreEx
{
    friend istream& operator>>(istream& is, MyIncreEx s);
    friend ostream& operator<<(ostream& os, MyIncreEx s);
    ...
};

The friend operators have a different and conflicting signature. You probably wanted to declare them as

    friend istream& operator>>(istream& is, MyIncreEx& s);
    friend ostream& operator<<(ostream& os, MyIncreEx const& s);

(assuming you also fix the output operator to work with MyIncreEx const& rather than MyIncreEx&).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top