C ++如何访问内部枚举类? [英] C++ How can I access to an inner enum class?

查看:108
本文介绍了C ++如何访问内部枚举类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++中遇到问题:

I am facing a problem in c++:

#include <iostream>
 class Apple{
public:
    int price = 100;
    enum class color {
    red =1, green, yellow
    };



};
int main() {
 Apple apple;
 std::cout << Apple::color::green << std::endl;

}

当我尝试编译此代码时,出现以下消息:

When I try to compile this code following message appears:


[错误]'Apple :: color'不是类或命名空间

[Error] 'Apple::color' is not a class or namespace


推荐答案

P0W的答案在两个方面都是正确的,但是如果您只想输出基础值,则强制转换而不是重载可能更简单。

P0W's answer is correct on both counts, but in case you simply want to output the underlying value, then it may be simpler to cast rather than overload the insertion operator.

using enum_type = std::underlying_type<Apple::color>::type;
enum_type value = (enum_type)Apple::color::green;
std::cout << value << '\n';

这篇关于C ++如何访问内部枚举类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆