问题
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