加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 可以重新定义constexpr和内联函数吗?

发布时间:2020-12-16 03:15:07 所属栏目:百科 来源:网络整理
导读:我正在核实C Primer的声明: Unlinke other functions,inline and constexpr functions may be defined multiple times in the program. 我使用下面的一个constexpr cfunc()的两个定义,期待foo_0()将调用第一个def,而foo_1()将调用第二个def.但尝试失败,编译
我正在核实C Primer的声明:

Unlinke other functions,inline and constexpr functions may be defined multiple times in the program.

我使用下面的一个constexpr cfunc()的两个定义,期待foo_0()将调用第一个def,而foo_1()将调用第二个def.但尝试失败,编译错误(最后).为什么?

constexpr int cfunc(){
  return 42;
}

int foo_0(){
  return cfunc();
}

constexpr int cfunc(){
  return 42;
}

int foo_1(){
  return cfunc();
}


int main(int argc,char **argv) {

  cout << foo_0() << endl;  
  cout << foo_1() << endl;  

  /* testconstexprfunc2.cpp:24:15: error: redefinition of ‘constexpr int cfunc()’ */
  /* testconstexprfunc2.cpp:16:15: error: ‘constexpr int cfunc()’ previously defined here */

  return 0;

}

解决方法

是的,与其他函数不同,在程序中可以定义多个内联和constexpr函数.但是,定义必须完全匹配.

按照标准说明:

从§7.1.5 / 2 constexpr指定器[dcl.constexpr]:

constexpr functions and constexpr constructors are implicitly inline.

从§3.2 / 6一个定义规则[basic.def.odr]:

There can be more than one de?nition of a class type (Clause 9),enumeration type (7.2),inline function with external linkage … in a program provided that each de?nition
appears in a di?erent translation unit…

来自§7.1.2 / 4功能规范[dcl.fct.spec]:

An inline function shall be de?ned in every translation unit in which it is odr-used and shall have exactly the same de?nition in every case.

因此,由于constexpr函数是隐含内联的,它具有内联函数的所有属性.因此,如果每个定义都出现在不同的翻译单元中,则constexpr函数可以有多个定义.

为什么你的程序失败:

在你的情况下,程序失败,因为你违反了这个规则.也就是说,您在同一个翻译单元(即main.cpp)中重新定义相同的constexpr函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读