gpt4 book ai didi

用于定义公共(public)变量 static const integer 的 C++ 标准

转载 作者:行者123 更新时间:2023-11-28 07:05:26 25 4
gpt4 key购买 nike

在c++中应该在哪里定义一个static const integer成员变量,是在定义它的类的头文件中还是在cpp文件中?

它符合两种情况,如果我将定义放在头文件中,如果我将定义移动到 cpp 文件中,但哪种是 c++ 标准?

最佳答案

以下是 C++ 标准关于常量静态成员的完整引用:

If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignmentexpression is a constant expression (5.19). A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.

因此,如果常量静态成员未被 ODR 使用,则不需要在类外定义它。

注意:顺便说一下,在这种情况下,const static 成员是否公开并不重要。

关于用于定义公共(public)变量 static const integer 的 C++ 标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21828806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com