I am attempting to override the <<
operator for a class. The purpose is basically to implement a toString()
like behavior for my class, so that sending it to cout
will produce useful output. Using a dummy example, I have the code below. When I attempt to compile, I get the foollowing error:
$ g++ main.cpp Rectangle.cpp /tmp/ccWs2n6V.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CRectangle const&)': Rectangle.cpp:(.text+0x0): multiple definition of `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CRectangle const&)' /tmp/ccLU2LLE.o:main.cpp:(.text+0x0): first defined here
I can't figure out why this is happening. my code is below:
Rectangle.h:
#include <iostream> using namespace std; class CRectangle { private: int x, y; friend ostream& operator<<(ostream& out, const CRectangle& r); public: void set_values (int,int); int area (); }; ostream& operator<<(ostream& out, const CRectangle& r){ return out << "Rectangle: " << r.x << ", " << r.y; }
Rectangle.cpp:
#include "Rectangle.h" using namespace std; int CRectangle::area (){ return x*y; } void CRectangle::set_values (int a, int b) { x = a; y = b; }
main.cpp:
#include <iostream> #include "Rectangle.h" using namespace std; int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; }
Multiple definitions for functions and operators can be created by using the concept of overloading. It is a declaration that contains the same name as declared in the various arguments used in the scope of the program.
If an object, a reference or a function is odr-used, its definition must exist somewhere in the program; a violation of that is usually a link-time error. struct S { static const int x = 0; // static data member // a definition outside of class is required if it is odr-used }; const int& f(const int& r); int n = b ? (
If you put a definition of a global variable in a header file, then this definition will go to every . c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With