在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
}
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以用C++完成这项工作吗?
是的,您可以使用虚函数作为接口的一部分,而不是使用if-else语句.
我举个例子:
class Sport
{
public:
virtual void ParseSport() = 0;
};
class Soccer : public Sport
{
public:
void ParseSport();
}
class Basket : public Sport
{
public:
void ParseSport();
}
Run Code Online (Sandbox Code Playgroud)
并以这种方式使用您的对象后:
int main ()
{
Sport *sport_ptr = new Basket();
// This will invoke the Basket method (based on the object type..)
sport_ptr->ParseSport();
}
Run Code Online (Sandbox Code Playgroud)
这要归功于C++添加了面向对象的功能.
您可以
1在编译时使用模板魔术为不同和不相关的类型执行不同的操作;
2在运行时使用继承和多态来对继承相关的类型执行不同的操作(如gliderkite和rolandXu的答案);
3使用C风格的switch语句enum(或其他整数类型).
编辑:(非常简单)使用模板的示例:
/// 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);
}
Run Code Online (Sandbox Code Playgroud)