Home > Net >  Error while trying to overload << operator
Error while trying to overload << operator

Time:09-17

I can't get the below code to compile while trying to overload the << operator. Can anyone point whats going wrong?

#include <iostream>

std::ostream& operator<<(std::ostream& i, int n)
{
    return i;
}

int main()
{
    std::cout << 5 << std::endl;
    std::cin.get();
    return 0;
}

CodePudding user response:

There is already defined the operator << for an object of the type int in the C standard library

basic_ostream<charT, traits>& operator<<(int n);

so this call of the operator in this statement

std::cout << 5 << std::endl;

is ambiguous because the standard operator is found due to the argument dependent lookup.

To disactivate the ADL you could write for example something like the following calling the operator explicitly with two arguments

#include <iostream>

std::ostream& operator<<(std::ostream& i, int n)
{
    return i.operator <<( n );
}

int main()
{
    operator <<( std::cout, 5 ) << std::endl;
    std::cin.get();
    
    return 0;
}

The program output is

5

Though it does not make a great sense.:)

CodePudding user response:

Because more than one operator "<<" matches these operands.

std::ostream& operator<<(std::ostream& i, int n) has been defined.

Operator can be overload, not override.

operator works like this:
TypeA a = (TypeB)operand1 operator (TypeC)operand2

see operator as a function, it translates to this func:
TypeA operator(TypeB operand1, TypeC operand2)

Define the func twice would cause compile error.

To overload <<, try:
std::ostream& operator<<(std::ostream& i, OtherType n)
or
AnyType operator<<(AnyType i, AnyType n)

Just do not repeat.

  • Related