error LNK2005 多次定义inline解决办法

在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-2010

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值