c++ - char 初始化枚举的基础类型应该是什么?

标签 c++ enums language-lawyer

回答这个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/

相关文章:

c++ - 类和方法上的模板是相关的。如何防止组合?

c++ - 必须使用 cin.getline() 输入两次

java - 一个枚举常量包含同一个枚举类的所有枚举常量

在界面中使用枚举的 typescript

c++ - 从 Qt 资源加载 Csv 文件

c++ - 如何创建 QList 的深拷贝 (Qt 4.8)

c# - 将 XML 值反序列化为枚举时处理额外空格

c++ - 是否保证 C++ 标准库容器调用可替换的新函数?

c++ - 数组新表达式中的直接初始化与列表初始化

c - 带有#include 指令的尾随字符