在vs2008下编译自己写的三维向量类头文件vec3f.h,有如下重载操作符成员:
#ifndef _VECTOR3F_
#define _VECTOR3F_
class vec3f
{
public:
...
vec3f& operator = (const vec3f &v);
...
};
vec3f& vec3f::operator = (const vec3f &v)
{
x = v.x;
y = v.y;
z = v.z;
return *this;
}
...
#endif
在多个源程序均包含vec3f.h时编译报错:
error LNK2005: "public: class vec3f & __thiscall vec3f::operator=(class vec3f const &)" (??4vec3f@@QAEAAV0@ABV0@@Z) already defined in pipeline.obj
错误是成员函数重复定义,网上找了下资料,发现若将成员函数定义为inline即可解决,或将函数实现放进一个单独的源文件中:
inline
vec3f& vec3f::operator = (const vec3f &v)
{
x = v.x;
y = v.y;
z = v.z;
return *this;
}
解决方法分析如下,引自http://stackoverflow.com/questions/11456159/lnk-2005-link-errors-for-functions-but-not-for-class-in-visual-studio-2010If you define something in a header file, then that definition will be duplicated in any translation unit (roughly speaking, every source file) that includes that header. Sometimes, multiple definitions are an error.
Classes can be defined in multiple translation units, as long as the definitions are identical; indeed, they must be defined in any translation unit that uses them.
Functions usually can't, but you can allow it by declaring it inline, or you could move the definition to a single source file, and only declare it in the header.