从大括号括起来的列表进行数组初始化的 C++ 怪异
C++ weirdness with array initialization from brace-enclosed lists
我无法使用 GCC 或 Clang 编译下面的代码。尝试了 C++11 和 C++14。
我的问题:
是否有任何合乎逻辑的理由不执行此操作?我自己,我想不出任何...请参阅下面的解决方法。
enum class fruit {
APPLES,
ORANGES,
STRAWBERRIES
};
struct Area {float x, y, width, height;};
const Area test[] = {
[fruit::APPLES] = {1,2,3,4},
[fruit::ORANGES] = {2,2,3,4},
[fruit::STRAWBERRIES] = {3,2,3,4}
};
这虽然编译得很好:
namespace fruit { // instead of enum class, this works
enum {
APPLES,
ORANGES,
STRAWBERRIES
};
}
struct Area {float x, y, width, height;};
const Area test[] = {
[fruit::APPLES] = {1,2,3,4},
[fruit::ORANGES] = {2,2,3,4},
[fruit::STRAWBERRIES] = {3,2,3,4}
};
好的,我会根据我在评论中学到的知识自己回答这个问题。
这显然是使用“指定初始化器”调用的,它是 C99 的一个特性,而不是 C++ 标准的一部分(即使它在某些情况下可以编译):
int array[] = {
[1] = 11,
[0] = 22
};
如果我进行这些更改,我的问题中的代码会为我编译:
[fruit::APPLES] = {1,2,3,4}
变为:
[(int)fruit::APPLES] = {1,2,3,4}
或成(更正确的方式):
[static_cast<int>(fruit::APPLES)] = {1,2,3,4}
但是如果你想与标准兼容,最好不要使用指定的初始化器,而是重写代码...
我无法使用 GCC 或 Clang 编译下面的代码。尝试了 C++11 和 C++14。
我的问题:
是否有任何合乎逻辑的理由不执行此操作?我自己,我想不出任何...请参阅下面的解决方法。
enum class fruit {
APPLES,
ORANGES,
STRAWBERRIES
};
struct Area {float x, y, width, height;};
const Area test[] = {
[fruit::APPLES] = {1,2,3,4},
[fruit::ORANGES] = {2,2,3,4},
[fruit::STRAWBERRIES] = {3,2,3,4}
};
这虽然编译得很好:
namespace fruit { // instead of enum class, this works
enum {
APPLES,
ORANGES,
STRAWBERRIES
};
}
struct Area {float x, y, width, height;};
const Area test[] = {
[fruit::APPLES] = {1,2,3,4},
[fruit::ORANGES] = {2,2,3,4},
[fruit::STRAWBERRIES] = {3,2,3,4}
};
好的,我会根据我在评论中学到的知识自己回答这个问题。
这显然是使用“指定初始化器”调用的,它是 C99 的一个特性,而不是 C++ 标准的一部分(即使它在某些情况下可以编译):
int array[] = {
[1] = 11,
[0] = 22
};
如果我进行这些更改,我的问题中的代码会为我编译:
[fruit::APPLES] = {1,2,3,4}
变为:
[(int)fruit::APPLES] = {1,2,3,4}
或成(更正确的方式):
[static_cast<int>(fruit::APPLES)] = {1,2,3,4}
但是如果你想与标准兼容,最好不要使用指定的初始化器,而是重写代码...