简体   繁体   English

class 命名空间中的 C++ 公共枚举

[英]C++ public enum in namespace of class

I am making a class and I want to create an enum inside that class so that it can only be accessed through the namespace of that class.我正在制作一个 class 并且我想在该 class 中创建一个枚举,以便只能通过该 class 的名称空间访问它。 I would want users to be able to access the enum outside of the class like so:我希望用户能够像这样访问 class 之外的枚举:

GpioPin pin(23, GpioPin::OUTPUT);

where GpioPin is the class and OUTPUT is one of the enum values.其中 GpioPin 是 class 和 OUTPUT 是枚举值之一。

I tried putting the enum at the top of the class and I tried putting it under the public label like (constructor included for help debugging):我尝试将枚举放在 class 的顶部,并尝试将它放在公共 label 下(包括用于帮助调试的构造函数):

public:
    enum pin_dir {
        INPUT,
        OUTPUT,
    };

    GpioPin(int pin_num, pin_dir dir): pin_num(pin_num), dir(dir) {
        std::string dir_str; 
        if(dir == INPUT){
            dir_str = "in";
        } else if (dir == OUTPUT){
            dir_str = "out";
        } else {
            std::cout << "invalid direction in constructor for pin " << pin_num << std::endl;
            return;
        }

        init_gpio_pin(pin_num, dir_str.c_str());
    }

but when under the public tag the constructor acts like the enum doesn't exist and throws a compiler error.但是当在公共标签下,构造函数的行为就像枚举不存在并引发编译器错误。

Does anyone know the proper way to do this?有谁知道这样做的正确方法?

Thanks谢谢

Edit: the problem has been solved.编辑:问题已解决。 The code that is depicted here is correct and works as intended.此处描述的代码是正确的并且按预期工作。 The accepted answer gives some good information about enum class in C++接受的答案提供了有关 C++ 中的枚举 class 的一些很好的信息

Look at enum class (google for c++ enum class).查看枚举 class (谷歌搜索 c++ 枚举类)。

Class Foo {
public:
    enum class Color{ Red, Green, Blue};
};

Then, you reference things as:然后,您将事物引用为:

Foo::Color::Red

Works great.效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM