我正在尝试为一个类覆盖<<
运算符。目的基本上是为了实现类似toString()
的行为,以便将其发送到cout
会产生有用的输出。使用一个虚拟的示例,我有以下代码。当我尝试编译时,我会得到以下错误:
$ 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
我无法理解为什么会发生这种情况。以下是我的代码: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;
}
主程序.cpp:
#include <iostream>
#include "Rectangle.h"
using namespace std;
int main () {
CRectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
CRectangle
上方有另一个类定义,并且在overload<<
中使用了CRectangle
的<<
,那么就会出现问题。即使进行了CRectangle
的前向声明!你知道为什么吗? - Paschalis