C++ Class Traffic Light with enum?

為{幸葍}努か 提交于 2021-01-24 12:14:10

问题


I have a TrafficLight C++ class and I have some doubts about using enum for color management, especially regarding the correct syntax to use. below I write simplified code pieces, since my intent is only to understand how it works:

class TrafficLight
{
private:
    // ...
    enum class color{
        GREEN,
        RED,
        YELLOW
    };
    // ...
public:
    TrafficLight(/* Want to pass the color here in the constructor */)
    {
        if(/* Color passed as argument is RED */)
            // do something...
        {}
        else
            // do something else...
        {}
    }
}; 

OtherClass: this class creates a TrafficLight object with a specified color:

class OtherClass
{
public:
    //...
    void createTrafficLight()
    {
        TrafficLight traffic_light(/* Color */);
    }
    //...
};

TrafficLIght and OtherClass are not in the same file.

I'm not sure what the syntax is for passing the color of the traffic light as an argument


回答1:


color can be used just like any other type and its enumerators can be accessed as if they were static members of a class:

    TrafficLight(color col)
    {
        if(col == color::RED)
            // do something...

    //...
    void createTrafficLight()
    {
        TrafficLight traffic_light(TrafficLight::color::RED);
    }

You will need to make enum class color public though, if code outside the class is supposed to be able to access it and its enumerators.




回答2:


You need first of all make you enum public, then include .h of trafficLight class in file where OtherClass is defined.

The code can be the following:

class TrafficLight
{
private:

public:

    // ...
    enum class color{
        GREEN,
        RED,
        YELLOW
    };
    // ...

    TrafficLight(color col)
    {
        if(col == color::RED)
            // do something...
        {}
        else
            // do something else...
        {}
    }
}; 

And the OtherClass need to include the .h where is defined the TrafficLight class

class OtherClass
{
public:
    //...
    void createTrafficLight()
    {
        TrafficLight traffic_light(TrafficLight::color::RED);
    }
    //...
};


来源:https://stackoverflow.com/questions/59426711/c-class-traffic-light-with-enum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!