gpt4 book ai didi

c++ - 为什么未定义范围的枚举声明可以编译?

转载 作者:搜寻专家 更新时间:2023-10-31 00:54:06 25 4
gpt4 key购买 nike

在 Scott Meyers 的 Effective Modern C++ 一书中提到,无作用域枚举和有作用域枚举(枚举类)之间的主要区别之一是我们不能前向声明前者(请参阅第3,第 10 项 - “首选范围内的枚举而不是非范围内的枚举”)。例如:

enum Color;            *// error!*
enum class Color; *// fine*

但是我写了下面提到的小例子,发现事实并非如此。

测试.h

#pragma once
enum names;
void print(names n);

测试.cpp

#include "test.h"

#include <iostream>

enum names { John, Bob, David };

void print(names n)
{
switch (n)
{
case John:
case Bob:
case David:
std::cout << "First names." << std::endl;
break;
default:
std::cout << "Other things" << std::endl;
};
}

main.cpp

#include "test.h"
#include <iostream>

int main()
{
names n = static_cast<names>(2);
print(n);
return 0;
}

我使用过 VC14 编译器 (Visual Studio 2015)。这是编译器的错误或功能吗?还有别的吗?如果这是错误或功能(考虑到迈耶斯说这是无范围枚举和有范围枚举之间的主要区别),则意味着编译器能够管理我们可以声明无范围枚举的情况。因此,是否需要在 enum 之后添加一个新的关键字 class?当然,有人会说作用域枚举还有另外两个特点。据我了解,上述功能是最重要的。

最佳答案

C++11

首先:C++11 允许前向声明无作用域的枚举。您只需将基础类型提供给编译器(示例来自 Effective Modern C++,第 3 章,第 10 项):

enum Color: std::uint8_t;

您使用的是编译器的非标准扩展,但无论如何都是可能的。

重要与否

Scott Meyers 在引用的章节中说:

It may seem that scoped enums have a third advantage over unscopedenums, because scoped enums may be forward-declared, i.e., their namesmay be declared without specifying their enumerators:[...] InC++11, unscoped enums may also be forward-declared, but only after abit of additional work.

“May seem”的意思是“is”的反义词。 Scott Meyers 本人表示这不是该书中的重要特征。

关于c++ - 为什么未定义范围的枚举声明可以编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com