Sunny Khandare
Sunny Khandare

Reputation: 59

Ambiguous Overload For operator "<<"

I am learning operator overloading in c++ and I want to know the ouput of following code

#include<iostream>
using namespace std;
class xyz
{

 public:
        int i;

    friend ostream & operator<<( ostream & Out , int);
};



ostream & operator<<(ostream & out , int i)
{
    cout<<10+i<<endl;
}


int main()
{
    xyz A;
    A.i=10;

    cout<<10;
}

And i got two errors

  1. error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘int’) cout<<10+i;

  2. error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘int’) cout<<10;

can anyone explain whats the problem ?

I want to know that what happens if I overload an "<<" operator for printing int with only one parameter int(obvious) and I just want to print an number separately like "cout<<10" int the above mentioned code. So how compiler will decide that which function should be called when i am trying to print just any integer number.

Upvotes: 1

Views: 7757

Answers (2)

jkj yuio
jkj yuio

Reputation: 2613


// this include brings std::ostream& operator<<(std::ostream&, int)
// into scope and therefore you cannot define your own later
#include<iostream>  

using namespace std;
class xyz
{

 public:
        int i;

    // needs body 
    friend ostream & operator<<( ostream & Out , int)
    {
        return Out;
    }
};



/* cant have this after including ostream
ostream & operator<<(ostream & out , int i)
{
    cout<<10+i<<endl;
}
*/


int main()
{
    xyz A;
    A.i=10;

    cout<<10;
}

Upvotes: 0

john
john

Reputation: 87944

So obviously the problem is that you have written ostream & operator<<(ostream & out , int i) when this already exists. But it's clear that what you meant to write is this

ostream& operator<<(ostream& out, const xyz& a) // overload for xyz not int
{
    out<<a.i<<endl; // use out not cout
    return out;     // and don't forget to return out as well
}

and this

int main()
{
    xyz A;
    A.i=10;

    cout<<A<<endl; // output A not 10
}

Upvotes: 3

Related Questions