Search code examples
c++operator-overloadingostream

Does Overloading Operator<< works inside the class?


I mean, I was trying to overload the operator<< inside the class

like this

 class A {
      public:
           ostream &operator<<(ostream &os);// which doesnt work

      private:
           friend ostream &operator<<(ostream &os, const A& a); //Works
           int i;

 };

  Definition
          ostream &operator<<(ostream &os, const A& a) {
              os<<a.i;
              return os;
          }

why can't I overload the operator inside the class specific to class? or Am I missing something? or Am I stupid to even think in such a way? Please advise.


Solution

  • The member function:

    ostream &operator<<(ostream &os);
    

    does work, but not for the situation you want. It will be called when you do something like:

    A a;
    a << std::cout;
    

    i.e. where the object is the left-hand side of the operator.