类之外的运算符重载!
当我试图分离非成员重载运算符的声明和实现时,我在 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 错误..我不明白为什么..
when i was trying to seperate the declaration and implementation of a non-member overloaded operator, i got a LNK2001 error in VC2010, my code was like this:
-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);
}
so once i use the '+' operation, the error pumps out, but if i remove the declaration in the header file, there are no LNK2001 errors.. i cannot figure out why..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑您的定义与声明位于不同的名称空间中。 ADL 正在查找声明(因为它与类位于同一命名空间中),然后在链接期间出现未解决的外部错误。
例如
-foo.h-
-foo.cpp-
将给出您所描述的错误。解决方案是将
operator+
定义放在正确的命名空间中:I suspect you have the definition in a different namespace than the declaration. ADL is finding the declaration (since it's in the same namespace as the class), and then you get an unresolved external error during link.
e.g.
-foo.h-
-foo.cpp-
Will give the error you describe. The solution is to put the
operator+
definition in the correct namespace:我看不出您提供的代码有什么问题。
您确定这正是您拥有的代码吗?
如果是,那么似乎唯一的解释是,假设您使用的是 Visual Studio,您以某种方式设法在 Visual Studio 项目中没有 [foo.cpp]。
如果使用命令行工具,相应的东西将不包括[foo.obj]。
如果这些评论没有帮助,您可以创建一个显示问题的单个文件小程序吗?
干杯,
I can't see anything wrong with the code you have presented.
Are you sure that this is exactly the code you have?
If it is, then it seems the only explanation is that you have somehow managed to not have [foo.cpp] in your Visual Studio project, assuming you're using Visual Studio.
If using command line tools, the corresponding thing would be not including [foo.obj].
If those comments don't help, can you create a single file small program that exhibits the problem?
Cheers,
将您的原型更改为(如果您出于某种原因坚持将operator+的定义保留在封闭的命名空间中)
Change your prototype to (if you insist on keeping the definition of operator+ in the enclosing namespace for whatever reason)