Q:

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

A:

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

