Alan
Alan

Reputation: 117

operator overloading outside of a class!

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..

Upvotes: 2

Views: 5608

Answers (3)

Chubsdad
Chubsdad

Reputation: 25497

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) 

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283624

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

Upvotes: 5

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

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,

Upvotes: 0

Related Questions