Why friend function is preferred to member function for operator<<

前端 未结 4 820
独厮守ぢ
独厮守ぢ 2021-02-10 06:38

When you are going to print an object, a friend operator<< is used. Can we use member function for operator<< ?

class A {

public:
void operator<         


        
4条回答
  •  温柔的废话
    2021-02-10 07:28

    A further reason in your example - it has to be a friend because that's the only way to define a free function inside the class definition. If you wanted a non-friend free function, it would have to be defined outside the class.

    Why would you prefer to define it in the class? Sometimes it's nice to define all the operators together:

    struct SomeClass {
        // blah blah blah
        SomeClass &operator+=(const SomeClass &rhs) {
            // do something
        }
        friend SomeClass operator+(SomeClass lhs, const SomeClass &rhs) {
            lhs += rhs;
            return lhs;
        }
        // blah blah blah
        // several pages later
    };
    

    might be a bit more user-friendly than:

    struct SomeClass {
        // blah blah blah
        SomeClass &operator+=(const SomeClass &rhs) {
            // do something
        }
        // blah blah blah
        // several pages later
    };
    
    SomeClass operator+(SomeClass lhs, const SomeClass &rhs) {
        lhs += rhs;
        return lhs;
    }
    

    This assumes of course that you are defining the related member functions in the class definition, rather that declaring them there and defining them in a .cpp file.

    Edit: I've used += and + as an example without really thinking about it, but your question is about operator<<, which doesn't have any closely related operators like operator+ does. But if operator<< calls one or more member functions related to printing, you might want to define it near where they're defined.

提交回复
热议问题