<< overload operator in a class in C ++

I have a class that uses struct, and I want to overload the <operator for this structure, but only inside the class:

typedef struct my_struct_t {
  int a;
  char c;
} my_struct;

class My_Class
{
  public:
    My_Class();
    friend ostream& operator<< (ostream& os, my_struct m);
}

I can only compile when I declare the operator <<overload with the keyword friend, but then the operator is overloaded everywhere in my code, and not just in the class. How to overload the <<statement for my_struct ONLY inside the class?

Edit: I want to use the overloaded print statement my_struct, which is a member of My_Class

+5
source share
3 answers

How to overload the <<statement for my_struct ONLY inside the class?

Define it as

static std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //...

or

namespace {
    std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //...
}

.cpp, MyClass.

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

+9

< - .

class My_Class
{
  public:
    My_Class();
 private:
    void Print( ostream & os, const my_struct & m );
};

, , .

: < < < , . , .

+10

If "only overloaded in My_Class" means only visible / used by my class, you can use a different overload than the member, which is only visible to My_Class. For example.

   struct my_struct {
      int a;
      char c;
   };

   class My_Class
   {
      publiC:
         My_Class();
   }

Then in My_Class.cpp:

namespace {
    ostream& operator(ostream& os, const my_struct& mystruct ) {
         os << mystruct.a << mystruct.c;
    }
}
+1
source

All Articles