[英]Another way to test the value of an enum in C++
在C中,我可以使用if / else语句测试枚举的值。 例如:
enum Sport {Soccer, Basket};
Sport theSport = Basket;
if(theSport == Soccer)
{
// Do something knowing that it is Soccer
}
else if(theSport == Basket)
{
// Do something knowing that it is Basket
}
还有其他方法可以用C ++完成这项工作吗?
是的,您可以使用虚函数作为接口的一部分,而不是使用if-else语句。
我举个例子:
class Sport
{
public:
virtual void ParseSport() = 0;
};
class Soccer : public Sport
{
public:
void ParseSport();
}
class Basket : public Sport
{
public:
void ParseSport();
}
并以这种方式使用您的对象后:
int main ()
{
Sport *sport_ptr = new Basket();
// This will invoke the Basket method (based on the object type..)
sport_ptr->ParseSport();
}
这要归功于C ++添加了面向对象的功能。
您可以
1在编译时使用模板魔术为不同和不相关的类型执行不同的操作;
2在运行时使用继承和多态来对继承相关的类型执行不同的操作(如gliderkite和rolandXu的答案);
3在enum
(或其他整数类型)上使用C样式的switch
语句。
编辑:(非常简单)使用模板的例子:
/// class template to be specialised
template<typename> struct __Action;
template<> struct __Action<Soccer> { /// specialisation for Soccer
static void operator()(const Soccer*);
};
template<> struct __Action<Badminton> { /// specialisation for Badminton
static void operator()(const Badminton*);
};
/// function template calling class template static member
template<typename Sport> void Action(const Sport*sport)
{
__Action()(sport);
}
你仍在测试C中的值,即枚举值,而不是theSport的类型。 C ++支持运行时类型检查,称为RTTI
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.