gpt4 book ai didi

c++ - 在类定义之外定义 static const

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:25:41 25 4
gpt4 key购买 nike

我们是否应该在类定义之外定义一个 static const 成员,即使它是在类内部初始化的?

#include<iostream>  
using namespace std;
class abc
{
static const int period=5;
int arr[period];
public:
void display()
{
cout<<period<<endl;
}
};

const int abc::period;

int main()
{
abc a;
a.display();
return 0;
}

注释完 //const int abc::period; 后,两个版本的代码在 gcc 4.3.4 上运行良好。所以我想问一下为什么这两个版本都有效,哪个版本符合标准?

最佳答案

您通过编写 const int abc::period;定义静态成员period。您可以为类的 static const 成员提供类内初始化程序,但这不是定义,而只是声明。

9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

即使没有定义,您的代码也能编译,因为您没有获取静态成员的地址。 Bjarne Stroustrup 在 C++-FAQ 中提到 here 当(且仅当)它具有类外定义时,您可以获取静态成员的地址

关于c++ - 在类定义之外定义 static const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6106194/

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