41

我试图覆盖<<一个类的运算符。目的基本上是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

我无法弄清楚为什么会这样。我的代码如下:

矩形.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;
}

矩形.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;
}
4

2 回答 2

61

你打破了单一定义规则。快速修复是:

inline ostream& operator<<(ostream& out, const CRectangle& r){
    return out << "Rectangle: " << r.x << ", " << r.y;
}

其他是:

  • 在头文件中声明运算符并将实现移动到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;
        }
};

奖金:

  • 使用包括警卫
  • using namespace std;从标题中删除。
于 2012-10-09T14:43:05.413 回答
20

您将函数的定义.h放在文件中,这意味着它将出现在每个翻译单元中,违反了一个定义规则(=>您operator<<在每个对象模块中定义,因此链接器不知道哪个是“正确的一”)。

您可以:

  • 在 .h 文件中只写你的操作符的声明(即它的原型)并将它的定义移动到rectangle.cpp
  • make operator<< inline-inline只要所有定义相同,就可以多次定义函数。

(此外,您应该在包含中使用标头保护。)

于 2012-10-09T14:45:07.360 回答