相关疑难解决方法(0)

为什么我不能在类中初始化非const静态成员或静态数组?

为什么我不能在类中初始化非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;
}
Run Code Online (Sandbox Code Playgroud)

编译器发出以下错误:

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 …
Run Code Online (Sandbox Code Playgroud)

c++ static const

93
推荐指数
3
解决办法
9万
查看次数

我们是否还需要单独定义静态成员,即使它们是在类定义中初始化的?

在C++ 03中,我们能够const static在类定义中内联初始化类数据成员,但是 如果要使用odr,仍然必须定义成员.

在C++ 11中仍然如此吗?

struct Foo
{
   static const int x = 3;
};

const int Foo::x;
// ^ required?
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer c++11

4
推荐指数
1
解决办法
319
查看次数

标签 统计

c++ ×2

c++11 ×1

const ×1

language-lawyer ×1

static ×1