c – 可以重新定义constexpr和内联函数吗?
我正在核实C Primer的声明:
我使用下面的一个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]:
从§3.2 / 6一个定义规则[basic.def.odr]:
来自§7.1.2 / 4功能规范[dcl.fct.spec]:
因此,由于constexpr函数是隐含内联的,它具有内联函数的所有属性.因此,如果每个定义都出现在不同的翻译单元中,则constexpr函数可以有多个定义. 为什么你的程序失败: 在你的情况下,程序失败,因为你违反了这个规则.也就是说,您在同一个翻译单元(即main.cpp)中重新定义相同的constexpr函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |