【发布时间】:2016-03-31 02:00:51
【问题描述】:
我有一个类,它的成员 itemType 只设置一次并且从不修改,但它在许多 if 语句中用于决定调用哪个函数。 由于 itemType 仅设置一次,因此可以避免在类中的 else 位置使用 if 语句。这将简化和清理代码,另外还可以节省 if 检查的开销。 我在考虑函数一个指针,我可以根据 itemType 值在构造函数中初始化。 有没有其他更好的方法可以做到这一点?
请注意原始类和代码库很大,我不能根据 itemtype 创建子类。
enum ItemTypes
{
ItemTypeA,
ItemTypeB,
};
class ItemProcessing
{
public:
//This function is called hundreds of times
void ProcessOrder(Order* order)
{
//This member itemType is set only once in the constructor and never modified again
//Is there a way to not check it all the time??
if (itemtype == ItemTypes::ItemTypeA )
{
ProcessTypeA(order)
}
else if (itemtype == ItemTypes::ItemTypeB )
{
ProcessTypeB(order)
}
}
ItemProcessing(ItemTypes itype)
{
itemtype = itype; //can I do something here like setting a function pointer so I dont have to check this property in ProcessOrder() and call the relevant function directly.
}
private:
ItemTypes itemtype;
void ProcessTypeA(Order*);
void ProcessTypeB(Order*);
};
【问题讨论】:
-
你考虑过函数指针吗?