我想为我创建的类定义运算符,我希望运算符是内联的我还希望定义在.cpp
文件中,而声明在.h
文件中我试图这样做:
矢量3D.h
class Vector3D
{
...
};
inline Vector3D operator+(Vector3D lv, const Vector3D& rv);
inline Vector3D operator-(Vector3D lv, const Vector3D& rv);
矢量3D.cpp
...
inline Vector3D operator+(Vector3D lv, const Vector3D& rv)
{
lv += rv;
return lv;
}
inline Vector3D operator-(Vector3D lv, const Vector3D& rv)
{
lv -= rv;
return lv;
}
在_tmain
函数中调用函数:
std::cout << v1 << "+" << v2 << "=" << v1+v2 << std::endl;
std::cout << v1 << "-" << v2 << "=" << v1-v2 << std::endl;
我得到错误:
1>RotateShapes.obj : error LNK2019: unresolved external symbol "class Vector3D __cdecl operator+(class Vector3D,class Vector3D const &)" (??H@YA?AVVector3D@@V0@ABV0@@Z) referenced in function _wmain
1>RotateShapes.obj : error LNK2019: unresolved external symbol "class Vector3D __cdecl operator-(class Vector3D,class Vector3D const &)" (??G@YA?AVVector3D@@V0@ABV0@@Z) referenced in function _wmain
如果我删除inline
然后一切正常。如果我不调用函数,则编译成功。有没有办法inline
在声明函数的不同位置定义函数?