如何ToString()在c ++中的枚举?

编程入门 行业动态 更新时间:2024-10-28 20:23:26
本文介绍了如何ToString()在c ++中的枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何ToString()在c ++中的枚举?在Java和C#中,我只调用ToString。

How do i ToString() an enum in c++? In Java and C# I would just call ToString.

enum Colours { Red =0, Green=1, Blue=2 };

我需要创建一个字符串:Invalid color'+ color +'selected。

I need to create a string like: "Invalid colour '" + colour + "' selected."

推荐答案

虽然这通常是通过交换机完成的,但我更喜欢数组:

While this is commonly done through switches, I prefer arrays:

#include <iostream> namespace foo { enum Colors { BLUE = 0, RED, GREEN, SIZE_OF_ENUM }; static const char* ColorNames[] = { "blue", "red", "green" }; // statically check that the size of ColorNames fits the number of Colors static_assert(sizeof(foo::ColorNames)/sizeof(char*) == foo::SIZE_OF_ENUM , "sizes dont match"); } // foo int main() { std::cout << foo::ColorNames[foo::BLUE] << std::endl; return 0; }

显式数组大小有利于生成编译时间

The explicit array size has the benefit of generating a compile time error should the size of the enum change and you forget to add the appropriate string.

或者,Boost存储库中有Boost.Enum。库尚未正式发布,但是相当稳定,并提供你想要的。但我不会推荐给新手。

Alternatively, there is Boost.Enum in the Boost vault. The library hasn't been officially released but is quite stable and provides what you want. I wouldn't recommend it to a novice though.

更多推荐

如何ToString()在c ++中的枚举?

本文发布于:2023-11-05 14:49:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561135.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ToString

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!