'friend' functions and << operator overloading: What is the proper way to overload an operator for a class?

前端 未结 3 1103
眼角桃花
眼角桃花 2020-11-28 03:25

In a project I\'m working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation

3条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 03:42

    Note: You might want to look at the operator overloading FAQ.


    Binary operators can either be members of their left-hand argument's class or free functions. (Some operators, like assignment, must be members.) Since the stream operators' left-hand argument is a stream, stream operators either have to be members of the stream class or free functions. The canonical way to implement operator<< for any type is this:

    std::ostream& operator<<(std::ostream& os, const T& obj)
    {
       // stream obj's data into os
       return os;
    }
    

    Note that it is not a member function. Also note that it takes the object to stream per const reference. That's because you don't want to copy the object in order to stream it and you don't want the streaming to alter it either.


    Sometimes you want to stream objects whose internals are not accessible through their class' public interface, so the operator can't get at them. Then you have two choices: Either put a public member into the class which does the streaming

    class T {
      public:
        void stream_to(std::ostream&) const {os << obj.data_;}
      private:
        int data_;
    };
    

    and call that from the operator:

    inline std::ostream& operator<<(std::ostream& os, const T& obj)
    {
       obj.stream_to(os);
       return os;
    }
    

    or make the operator a friend

    class T {
      public:
        friend std::ostream& operator<<(std::ostream&, const T&);
      private:
        int data_;
    };
    

    so that it can access the class' private parts:

    inline std::ostream& operator<<(std::ostream& os, const T& obj)
    {
       os << obj.data_;
       return os;
    }
    

提交回复
热议问题