Why is a friend function preferable to a member function for the << operator

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

class A {

public:
void operator<<(ostream& i) { i<<"Member function";}
friend ostream& operator<<(ostream& i, A& a) { i<<"operator<<"; return i;}
};


int main () {

   A a;
   A b;
   A c;
   cout<<a<<b<<c<<endl;
   a<<cout;
  return 0;
}

One point is that the friend function allows us to use it as follows

cout<<a<<b<<c

What other reasons?

+5
source share
4 answers

You should use a free function, not a member function, since for binary operators the left side is always *thisfor member functions, and the right side is passed as another parameter.

, , , , .

- :

myObject >> std::cout;

, , - >>.

: , , friend, .

+11

- .

, , friend. , . , :

template <class A, class B>
std::ostream& operator<<(std::ostream& os, const std::pair<A, B>& p)
{
  return os << '(' << p.first << ", " << p.second << ')';
}

, , first second .

+10

- friend, . , , .

? :

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
};

, :

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;
}

, - , .cpp.

: + = + , , operator<<, - , operator+. operator<< -, , , .

+1

. , , . ,

 ostream& operator<<(ostream& os, Myclass& obj)
{
   return obj.print(os);
}

ostream& MyClass::print(ostream& os)
{
   os << val; // for example.
   return os;
}
0

All Articles