c++ multiple definitions of operator<<

前端 未结 2 532
执笔经年
执笔经年 2020-12-08 06:50

I am attempting to override the << operator for a class. The purpose is basically to implement a toString() like behavior for my class, so t

2条回答
  •  盖世英雄少女心
    2020-12-08 07:18

    You're breaking the one definition rule. A quick-fix is:

    inline ostream& operator<<(ostream& out, const CRectangle& r){
        return out << "Rectangle: " << r.x << ", " << r.y;
    }
    

    Others are:

    • declaring the operator in the header file and moving the implementation to Rectangle.cpp file.
    • define the operator inside the class definition.

    .

    class CRectangle {
        private:
            int x, y;
        public:
            void set_values (int,int);
            int area ();
            friend ostream& operator<<(ostream& out, const CRectangle& r){
              return out << "Rectangle: " << r.x << ", " << r.y;
            }
    };
    

    Bonus:

    • use include guards
    • remove the using namespace std; from the header.

提交回复
热议问题