c++ multiple definitions of operator<<

前端 未结 2 514
执笔经年
执笔经年 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.
    0 讨论(0)
  • 2020-12-08 07:20

    You are putting the definition of a function in a .h file, which means that it will appear in every translation unit, violating the One Definition Rule (=> you defined operator<< in every object module, so the linker doesn't know which is "the right one").

    You can either:

    • write just the declaration of your operator (i.e. its prototype) in the .h file and move its definition to rectangle.cpp
    • make operator<< inline - inline functions are allowed to be defined more than once, as long as all the definitions are identical.

    (Also, you should use header guards in your includes.)

    0 讨论(0)
提交回复
热议问题