开发者

operator overloading outside of a class!

开发者 https://www.devze.com 2023-01-23 18:52 出处:网络
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:

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;
开发者_JAVA技巧};
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..


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-

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);
}

Will give the error you describe. The solution is to put the operator+ definition in the correct namespace:

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


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,


Change your prototype to (if you insist on keeping the definition of operator+ in the enclosing namespace for whatever reason)

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

精彩评论

暂无评论...
验证码 换一张
取 消