Question

I have a class that uses a struct, and I want to overload the << operator for that struct, but only within 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 w/ the friend keyword, but then the operator is overloaded everywhere in my code, not just in the class. How do I overload the << operator for my_struct ONLY within the class?

Edit: I will want to use the overloaded operator to print a my_struct which IS a member of My_Class

Was it helpful?

Solution

How do I overload the << operator for my_struct ONLY within 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 ) { //...
}

in the .cpp file in which you implement MyClass.

EDIT: If you really, really need to scope on the class and nothing else, then define it as a private static function in said class. It will only be in scope in that class and it's subclasses. It will hide all other custom operator<<'s defined for unrelated classes, though (again, only inside the class, and it's subclasses), unless they can be found with ADL, or are members of std::ostream already.

OTHER TIPS

Don't use operator <<. Use a named member function, and make it private.

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

Note you should pass the structure as a const reference, whichever method you use.

Edit: There is no need to make the operator << a member of the class just so you can use it to print a member of the class. You can make it a friend of the struct, or a completely free function, which the class then uses.

If by "only overloaded in the My_Class" you mean only visible / usable by my class you could use a non-member overload that's only visible to My_Class. E.g.

   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;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top