回答这个question about enums时我阅读了有关基础大小的规范,它说(关于无范围枚举)[7.5.5]:
If the underlying type is not fixed, the type of each enumerator is the type of its initializing value
但是当我尝试 following code我得到所有枚举的 sizeof int
(在 g++、VC 和 clang 上测试)。
#include <iostream>
using namespace std;
enum e1 { e1a };
enum class ec1 { ec1a };
enum e2 { e2a = 'a' }; // I expect this to have sizeof 1
enum class ec2 { ec2a = 'a' };
int main() {
cout << "plain enum:" << sizeof(e1a) << endl;
cout << "enum class:" << sizeof(ec1::ec1a) << endl;
cout << "char initialized plain enum:" << sizeof(e2a) << endl;
cout << "char initialized enum class:" << sizeof(ec2::ec2a) << endl;
}
输出:
plain enum: 4
enum class:4
char initialized plain enum: 4
char initialized enum class: 4
我误会了什么?
最佳答案
你错过了这句话:
Following the closing brace of an enum-specifier, each enumerator has the type of its enumeration.
证明:
#include <iostream>
using namespace std;
enum e1 { e1a };
enum class ec1 { ec1a };
enum e2 {
e2a = 'a' ,
e2b = sizeof(e2a) // <-- here the type of e2a is still char
};
// <-- here the type of e2a becomes the same as the type of e2 (i.e. int)
enum class ec2 { ec2a = 'a' };
int main() {
cout << "plain enum:" << sizeof(e1a) << endl;
cout << "enum class:" << sizeof(ec1::ec1a) << endl;
cout << "char initialized plain enum:" << sizeof(e2a) << " but e2b=" << e2b <<endl;
cout << "char initialized enum class:" << sizeof(ec2::ec2a) << endl;
}
输出:
plain enum:4
enum class:4
char initialized plain enum:4 but e2b=1
char initialized enum class:4
关于c++ - char 初始化枚举的基础类型应该是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38347643/