C++ Operator overloading example

前端 未结 3 1678
终归单人心
终归单人心 2021-01-25 19:08

Well, I\'m new to operator overloading, and I found this problem. Instead of documenting myself, I prefer to ask you :D

The point is, I know how to do simple operator ov

相关标签:
3条回答
  • 2021-01-25 19:41

    It's quite easy, don't panic :)

    You have recognized the problem well: it's very similar to the std::cout - std::endl work.

    You could do like such, though I'll rename the types, if you don't mind.

    struct EndMarker {};
    extern const EndMarker end; // To be defined in a .cpp
    
    class Data
    {
    public:
      Data(): m_data(1, "") {}
    
      // Usual operator
      template <class T>
      Data& operator<<(const T& input)
      {
        std::ostringstream aStream;
        aStream << input;
        m_data.back() += aStream.str();
      };
    
      // End of object
      Data& operator<<(EndMarker) { m_data.push_back(""); }
    
    private:
      std::vector<std::string> m_data;
    }; // class Data
    

    It works by adding to the current last element by default, and pushing an empty element at the end.

    Let's see an example:

    Data data;
    data << 1 << "bla" << 2 << end << 3 << "foo" << end;
    
    // data.m_data now is
    // ["1bla2", "3foo", ""]
    

    The other solution would be to keep a flag (boolean) to store if a end has been streamed or not, and if it has, creating a new element on the next insertion (and erasing the flag).

    It a bit more work on insertion, but you don't have the empty element... your call.

    0 讨论(0)
  • 2021-01-25 19:48

    The trick is to return a reference to youself from operator << - this way, the operator can be 'stacked'.

    class me {
    
        me& operator<<(int t) {...; return *this;}
    };
    
    me m;
    m << 4 << 5 << 6;
    

    Just overload the shift operator for all types you wish to support (or make it a template if you can afford the danger)!

    0 讨论(0)
  • 2021-01-25 19:53
    template <typename T>
    dxfdata & operator <<( dxfdata & d, const T & t ) {
       std::ostringstream os;
       os << t;
       d.b += os.str();
       return d;
    }
    
    0 讨论(0)
提交回复
热议问题