我正在尝试的是使用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之前一样在类外定义?
&Fruit::VALUES[1]
),它必须存在于某个地方。这个“某个地方”就是源文件中的这个定义。 - PiotrNyczconstexpr
,但我不知道如何同时初始化:(1)C++03的类外初始化和(2)C++11的类内初始化。 - jww#if __cplusplus < 201103L
#define DECLARE_FRUIT_VALUES
#define DEFINE_FRUIT_VALUES = { APPLE, ORANGE, BANANA, NONE }
#else
#define DECLARE_FRUIT_VALUES = { APPLE, ORANGE, BANANA, NONE }
#define DEFINE_FRUIT_VALUES
- PiotrNyczstatic constexpr Value VALUES[4] DECLARE_FRUIT_VALUES;
Value Fruit::Value[4] DEFINE_FRUIT_VALUES;
- PiotrNycz