8

这就是我正在尝试的。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;
}

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

>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

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

4

1 回答 1

17

test.cpp:9:66:错误:类内初始化非整数类型的静态数据成员“const Fruit::Value Fruit::VALUES [4]”需要“constexpr”[-fpermissive]

编译器告诉我们缺少什么:

class Fruit
{
public:
    enum Value { APPLE, ORANGE, BANANA, NONE };
    static constexpr Value VALUES[4] = { APPLE, ORANGE, BANANA, NONE };
    //     ^^^^^^^^^
...
};

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

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

constexpr Fruit::Value Fruit::VALUES[4];

编辑:由于 c++17 我们有内联变量,并且每个 constexpr 变量都是内联的,所以在 C++17 中问题得到了解决。

于 2012-11-05T00:05:56.243 回答