c++ multiple definitions of operator

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.

Leave a Comment