I want to define operators for a class I created, I want the operators to be inline I also want the definition be in the .cpp
file while the declaration is in the .h
file I tried to do this:
Vector3D.h
class Vector3D
{
...
};
inline Vector3D operator+(Vector3D lv, const Vector3D& rv);
inline Vector3D operator-(Vector3D lv, const Vector3D& rv);
Vector3D.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;
}
In the _tmain
function the functions are called:
std::cout << v1 << "+" << v2 << "=" << v1+v2 << std::endl;
std::cout << v1 << "-" << v2 << "=" << v1-v2 << std::endl;
I get the errors:
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
If I remove the inline
then everything works fine. If I don't call the functions, then compilation is successful. Is there a way to define an inline
function in a different place of where it was declared?
From the standard §3.2/3:
An inline function shall be defined in every translation unit in which it is odr-used.
If you don't define the functions in the header where they're declared inline, then how else do you get the definition into all compilation units that use them?
Sure, you can define the functions in a separate file and include it in the header. They'll technically be in a separate file, but after preprocessing, they'll be part of the header (and then, part of all compilation units which include the header). If that's not what you want, then you can't declare the functions inline.