运算符在类之外重载!

时间:2010-11-08 03:51:57

标签: c++ namespaces operator-overloading definition

当我试图分离非成员重载运算符的声明和实现时,我在VC2010中遇到了LNK2001错误,我的代码是这样的:

-foo.h -

class A
{
public:
    A(float x);
    float x;
};
A operator +(const A&, const A&);

-foo.cpp -

A::A(float x)
{
    this->x = x;
}

A operator +(const A& lh, const A& rh)
{
    return A(lh.x + rh.x);
}

所以一旦我使用'+'操作,错误泵出,但如果我删除头文件中的声明,没有LNK2001错误..我无法弄清楚为什么..

3 个答案:

答案 0 :(得分:5)

我怀疑你在与声明不同的命名空间中有定义。 ADL正在查找声明(因为它与类在同一名称空间中),然后在链接期间出现未解决的外部错误。

e.g。

-foo.h -

namespace aspace
{
  class A
  {
  public:
      A(float x);
      float x;
  };
  A operator +(const A&, const A&);
}

-foo.cpp -

#include "foo.h"
using namespace aspace;

A::A(float x)
{
    this->x = x;
}

A operator +(const A& lh, const A& rh)
{
    return A(lh.x + rh.x);
}

会给出您描述的错误。解决方案是将operator+定义放在正确的命名空间中:

namespace aspace
{
  A operator +(const A& lh, const A& rh)
  {
      return A(lh.x + rh.x);
  }
}

答案 1 :(得分:0)

我看不出您提供的代码有什么问题。

你确定这正是你的代码吗?

如果是,那么似乎唯一的解释是你在Visual Studio项目中设法没有[foo.cpp],假设你正在使用Visual Studio。

如果使用命令行工具,相应的东西将不包括[foo.obj]。

如果这些评论无效,您是否可以创建一个显示问题的单个文件小程序?

干杯,

答案 2 :(得分:0)

将原型更改为(如果您因任何原因坚持将operator +的定义保留在封闭的命名空间中)

A aspace::operator +(const A& lh, const A& rh)