Ala*_*lan 2 c++ namespaces operator-overloading definition
当我试图分离非成员重载运算符的声明和实现时,我在VC2010中遇到LNK2001错误,我的代码是这样的:
-foo.h-
class A
{
public:
A(float x);
float x;
};
A operator +(const A&, const A&);
Run Code Online (Sandbox Code Playgroud)
-foo.cpp-
A::A(float x)
{
this->x = x;
}
A operator +(const A& lh, const A& rh)
{
return A(lh.x + rh.x);
}
Run Code Online (Sandbox Code Playgroud)
所以一旦我使用'+'操作,错误泵出,但如果我删除头文件中的声明,没有LNK2001错误..我无法弄清楚为什么..
我怀疑你在与声明不同的命名空间中有定义.ADL正在查找声明(因为它与类在同一名称空间中),然后在链接期间出现未解决的外部错误.
例如
-foo.h-
namespace aspace
{
class A
{
public:
A(float x);
float x;
};
A operator +(const A&, const A&);
}
Run Code Online (Sandbox Code Playgroud)
-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);
}
Run Code Online (Sandbox Code Playgroud)
会给出你描述的错误.解决方案是将operator+定义放在正确的命名空间中:
namespace aspace
{
A operator +(const A& lh, const A& rh)
{
return A(lh.x + rh.x);
}
}
Run Code Online (Sandbox Code Playgroud)