overload operator<< within a class in c++

前端 未结 3 1740
傲寒
傲寒 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:07

    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.

    0 讨论(0)
  • 2021-01-06 01:16

    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.

    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题