Home > Mobile >  When overloading operator << inside a class, why I must declare it as a friend function despit
When overloading operator << inside a class, why I must declare it as a friend function despit

Time:12-28

I am trying to overload operator '<<' inside a class, but it's a must to declare it as a friend function otherwise the compiler would through into error: binary'operator<<' has too many parameters This is my function prototype:

ostream& operator<< (ostream& sout, const SimpleVector v);

I understand that friend function is used if I want to implement the function outside the class and access non-public class member, but this time I am implementing the function inside the class why do I need to use friend keyword

CodePudding user response:

If you really want to define the stream operator inside your class you need to omit the argument const SimpleVector v because it is already in the this pointer. However with that you cannot use the operator as usual (because of missing uniform function call syntax):

std::cout << SimpleVector() << std::endl;

because this calls the free function

operator<<(std::ostream&, const SimpleVector);

You would need to call the member function in a cumbersome way:

SimpleVector v;
v.operator<<(std::cout) << std::endl;

CodePudding user response:

Npn-static member functions are considered to have an extra parameter, called the implicit object parameter, which represents the object for which member functions have been called. There is a convention that the implicit object parameter, if present, is always the first parameter and the implied object argument, if present, is always the first argument.

So this declaration within a class

ostream& operator<< (ostream& sout, const SimpleVector v);

implies that the function has three parameters while the overloaded operator << is a binary operator.

When such a function is declared as a friend function then neither implicit parameter that refers to an object of a class is present.

I understand that friend function is used if I want to implement the function outside the class

You may implement a friend function within a class definition.

Functions are declared as friend functions to make it possible to access private and protected members of classes within friend functions.

  • Related