c++ multiple definitions of operator&

本农最近在啃c++ primer 5th,做练习,

Query operator&(const Query &lhs, const Query &rhs)
{
    return std::shared_ptr<Query_base>(new AndQuery(lhs, rhs));
}

inline Query operator|(const Query &lhs, const Query &rhs)
{
    return std::shared_ptr<Query_base>(new OrQuery(lhs, rhs));
}

手贱,删掉了

inline 

编译报错

multiple definitions of operator&.

最终,本农找到了原因.
按照大神们的说法,就是将函数定义写在header里,破坏了c++要求的One Definition Rule:
如下描述,按照我的理解,就是说,编译时,编译器会将各个cpp链接成obj,比如针对多个使用operator& 这个function的模块,都包含这个header,但是最终调用的都是obj里的这个function,所以将operator&写在cpp里没有问题,不存在multiple definitions.
而测试程序图方便,直接将definition写到header里,这样,每个使用operator& 这个function的模块,都包含这个header,等于每包含一次header,都重新定义了一遍,就是所谓的multiple definitions,所以报错.解决方案就是写到cpp里或function声明前加inline,因为inline允许多次定义.

如下是原文链接:
You are putting the definition of a function in a .h file, which means that it will appear in every translation unit, violating the One Definition Rule (=> you defined operator<< in every object module, so the linker doesn’t know which is “the right one”).
c++ multiple definitions of operator<<

如下是One Definition Rule原文链接:
What exactly is One Definition Rule in C++?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值