Search code examples
c++operator-overloadingambiguous

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


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:

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);
    friend MyIncreEx operator++(MyIncreEx& d); 

public:
    int num1 = 0, num2 = 0, num3 = 0;
};

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)              
{
    d.num1++;
    d.num2++;
    d.num3++;
    return d;
};

MyIncreEx operator++(MyIncreEx& d, int dummy) 
{
    d.num1++;
    d.num2++;
    d.num3++;
    return d;
};

int main()
{
    MyIncreEx obj;

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

Solution

  • 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&).