C++ 11初始化类静态const数组

use*_*322 8 c++ gcc c++11 gcc4.7

这是我正在尝试的.MinGW g ++ 4.7.0.

#include <iostream>
#include <string>

class Fruit
{
public:
    enum Value { APPLE, ORANGE, BANANA, NONE };
    static const Value VALUES[4] = { APPLE, ORANGE, BANANA, NONE };
    Fruit (Value v = NONE) : v_(v) { };
    std::string to_string () const {
        switch (v_) {
            case APPLE: return "apple";
            case ORANGE: return "orange";
            case BANANA: return "banana";
            default: return "none";
        }
    }
private:
    Value v_;
};

int main (int argc, char * argv[])
{
    for (Fruit f : Fruit::VALUES)
        std::cout << f.to_string() << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我尝试编译它并得到以下输出:

>g++ -std=c++0x test.cpp
test.cpp:9:66: error: 'constexpr' needed for in-class initialization of static d
ata member 'const Fruit::Value Fruit::VALUES [4]' of non-integral type [-fpermis
sive]


>g++ -std=c++0x -fpermissive test.cpp
test.cpp:9:66: warning: 'constexpr' needed for in-class initialization of static
 data member 'const Fruit::Value Fruit::VALUES [4]' of non-integral type [-fperm
issive]
cc1l4Xgi.o:test.cpp:(.text+0x1a): undefined reference to `Fruit::VALUES'
collect2.exe: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

C++ 11是否允许在类这样的类中初始化静态const数组?或者它是否必须像C++ 11之前一样在类外定义?

Pio*_*ycz 17

test.cpp:9:66:错误:'constexpr'需要静态d ata成员'const Fruit :: Value Fruit :: VALUES [4]'的非整数类型[-fpermis sive]的类内初始化

编译器告诉你缺少什么:

class Fruit
{
public:
    enum Value { APPLE, ORANGE, BANANA, NONE };
    static constexpr Value VALUES[4] = { APPLE, ORANGE, BANANA, NONE };
    //     ^^^^^^^^^
...
};
Run Code Online (Sandbox Code Playgroud)

cc1l4Xgi.o:test.cpp :(.text + 0x1a):对"Fruit :: VALUES"的未定义引用

要使链接器满意,必须在源文件(不是头文件)中的某处添加此行:

constexpr Fruit::Value Fruit::VALUES[4];
Run Code Online (Sandbox Code Playgroud)

  • @liuyanghejerry这里有两个不同的东西.首先是初始化,从C++ 03开始,它允许在整数类型的头中.正如您所看到的,只要它们是constexpr,这个C++特性就在C++ 11中针对其他类型进行了扩展.另一件事就是这个const成员的记忆空间.如果你采用这种变量的地址(`&Fruit :: VALUES [1]`)它必须存在于某个地方.这个"某处"只是源文件中的这个定义. (2认同)