【发布时间】:2012-03-28 06:06:47
【问题描述】:
为什么我不能在类中初始化非 const static 成员或 static 数组?
class A
{
static const int a = 3;
static int b = 3;
static const int c[2] = { 1, 2 };
static int d[2] = { 1, 2 };
};
int main()
{
A a;
return 0;
}
编译器发出以下错误:
g++ main.cpp
main.cpp:4:17: error: ISO C++ forbids in-class initialization of non-const static member ‘b’
main.cpp:5:26: error: a brace-enclosed initializer is not allowed here before ‘{’ token
main.cpp:5:33: error: invalid in-class initialization of static data member of non-integral type ‘const int [2]’
main.cpp:6:20: error: a brace-enclosed initializer is not allowed here before ‘{’ token
main.cpp:6:27: error: invalid in-class initialization of static data member of non-integral type ‘int [2]’
我有两个问题:
-
为什么我不能在类中初始化
static数据成员? - 为什么我不能在课堂上初始化
static数组,甚至是const数组?
【问题讨论】:
-
我认为主要原因是很难做对。原则上,你可能会做你所说的,但会有一些奇怪的副作用。就像您的数组示例被允许一样,那么您可能能够获得 A::c[0] 的值,但不能将 A::c 传递给函数,因为这需要一个地址和编译时间常量没有地址。 C++11 通过使用 constexpr 实现了其中的一些功能。
-
很好的问题和完美的答案。帮助我的链接:msdn.microsoft.com/en-us/library/0e5kx78b.aspx