Left shift operator overload

I researched and found out that when you want to overload the output stream operator for cout, then the correct way to do it is as follows:

std::ostream& operator<<(std::ostream& os, const T& obj)

This function must be defined outside the class, because what happens here is that the <operator is actually a friend function defined in ostream, and you use it. But, the question is, how exactly is this function defined in ostream? Since this function takes 2 parameters, and the second parameter is user-defined, there is no way that they can guess what is happening there.

Overloading for a specific class should look like this:

std::ostream& operator<<(std::ostream& os, const MyClass& obj)

How does the compiler / library accept the general definition for the second parameter, especially since in C ++ there is no such thing as a general class (such as Object in Java)?

+4
source share
2 answers

I think you are confused here:

the <<operator is actually a friend function defined in ostream, and you use it.

It is true that operator <<is determined within class std::ostream. In fact, it has several versions. But this does not concern us. In addition, they are not functions friend: by definition, a function friendis defined outside the class, it is a friend.

, operator << , , << ( std::ostream&).

TemplateRex, . , , , A B:

  • - A B
  • A B.

- . ( , , , ). , :

ostream? 2 , , , ,

, ostream. - , .

+5

++ , .. , . , - . , . Core ++ Stephan T. Lavavej.

S N ( ) operator<<(ostream&, S const&) .

namespace N {

class S 
{
    // bla
};

std::ostream& operator<<(std::ostream& os, S& const& obj)
{
    // print in terms of public interface of S
    // (else, deckare this a friend function inside S)
    return os;
}

} // N

int main()
{
    std::cout << S(); // operator<<(ostream&, S const&) is the best match
}

, , , . std ( ) N ( operator<<(ostream&, S const&)). , , - ( , , ).

, "" .

: " ", " ", , .

+1

Source: https://habr.com/ru/post/1530769/


All Articles