[英]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.