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
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:
Rectangle.cpp file..
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:
using namespace std; from the header.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:
rectangle.cppoperator<< 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.)