overload operator<< within a class in c++

前端 未结 3 1841
傲寒
傲寒 2021-01-06 00:40

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 {
  in         


        
3条回答
  •  被撕碎了的回忆
    2021-01-06 01:26

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

提交回复
热议问题