ewo*_*wok 27 c++ overriding iostream operator-keyword
我试图覆盖<<一个类的运算符.目的基本上是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
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚为什么会这样.我的代码如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
Luc*_*ore 42
你打破了一个定义规则.快速修复是:
inline ostream& operator<<(ostream& out, const CRectangle& r){
return out << "Rectangle: " << r.x << ", " << r.y;
}
Run Code Online (Sandbox Code Playgroud)
其他人是:
Rectangle.cpp文件..
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;
}
};
Run Code Online (Sandbox Code Playgroud)
奖金:
using namespace std;从标题中删除.Mat*_*lia 16
您将函数的定义放在一个.h文件中,这意味着它将出现在每个翻译单元中,违反了一个定义规则(=>您operator<<在每个对象模块中定义,因此链接器不知道哪个是"正确的"一").
你可以:
rectangle.cppoperator<< inline- inline只要所有定义都相同,就可以多次定义函数.(此外,您应该在包含中使用标题保护.)
| 归档时间: |
|
| 查看次数: |
23885 次 |
| 最近记录: |