类内的C++静态常量数组初始化

问题描述

我想创建一个常量和静态整数数组作为公共类变量。 定义它并立即初始化它是很好的。有关完整示例,请参阅下面的代码

#include <iostream>

class Foo {
public:
    constexpr static int arr[3][2] = {
            {1,2},{3,4},{5,6}
    };
};

int main() {
    for (int i = 0; i < 3; i++) {
        std::cout << "Pair " << Foo::arr[i][0] << "," << Foo::arr[i][1] << std::endl;
    }
    return 0;
}

然而,使用 g++ --std=c++11 test.cpp 编译上面的代码会产生

/usr/bin/ld: /tmp/ccc7DFI5.o: in function `main':
test.cpp:(.text+0x2f): undefined reference to `Foo::arr'
/usr/bin/ld: test.cpp:(.text+0x55): undefined reference to `Foo::arr'
collect2: error: ld returned 1 exit status

这在 C++ 中是不可能的吗?我更有可能遗漏了有关 C++ 及其静态变量初始化策略的某些部分。

解决方法

在 C++17(所以 C++11 和 C++14)之前,你必须添加

constexpr int Foo::arr[3][2];

在类的主体之外。

,

编译器错误是由 Could not set the List property 标准引起的。

通过使用 C++11 标准编译上面的代码

C++17

不会产生任何错误。

编辑:此解决方案适用于 g++ --std=c++17 test.cpp 而不是 C++17,如我原来的问题。对于 C++11 解决方案,请参阅已接受的答案。