Can a C++ enum class have methods?(C++ 枚举类可以有方法吗?)
问题描述
我有一个带有两个值的枚举类,我想创建一个接收值的方法并返回另一个.我还想保持类型安全(这就是我使用枚举类而不是枚举的原因).
I have an enum class with two values, and I want to create a method which receives a value and returns the other one. I also want to maintain type safety(that's why I use enum class instead of enums).
http://www.cplusplus.com/doc/tutorial/other_data_types/ 没有提到任何关于方法的内容然而,我的印象是任何类型的类都可以有方法.
http://www.cplusplus.com/doc/tutorial/other_data_types/ doesn't mention anything about methods However, I was under the impression that any type of class can have methods.
推荐答案
不,他们不能.
我可以理解,C++11 中强类型枚举的 enum class
部分似乎暗示您的 enum
具有 class
特质也是如此,但事实并非如此.我有根据的猜测是,关键字的选择受到了我们在 C++11 之前用于获取作用域枚举的模式的启发:
I can understand that the enum class
part for strongly typed enums in C++11 might seem to imply that your enum
has class
traits too, but it's not the case. My educated guess is that the choice of the keywords was inspired by the pattern we used before C++11 to get scoped enums:
class Foo {
public:
enum {BAR, BAZ};
};
然而,这只是语法.同样,enum class
不是 class
.
However, that's just syntax. Again, enum class
is not a class
.
这篇关于C++ 枚举类可以有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 枚举类可以有方法吗?
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01