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
Define it as
or
in the
.cppfile in which you implementMyClass.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 ofstd::ostreamalready.