首先,這是一個後續的問題這一個:How do I remove code duplication between similar const and non-const member functions?如何在抽象類中刪除類似的const和非const成員函數之間的代碼重複?
比方說,我有一個抽象類,提供了一個純虛函數:
class ICommand
{
public:
virtual ~ICommand() {};
virtual int Execute() = 0;
protected:
ICommand() {};
};//class ICommand
而另一個類從這個繼承:
class cCommand : public ICommand
{
public:
cCommand() {};
virtual ~cCommand() {};
virtual int Execute()
{
int retval = 0;
//do something and return appropriate error code
return retval;
}
};//class cCommand
現在我需要一個指針類型的ICommand的目的,但與常數數據,如:
//using a smart pointer here would be better, but it shows the problem
ICommand const * p = new cCommand();
int retval = p->Execute(); //won't compile
問題是,我在一個const對象上調用一個非const成員函數。 所以我要麼在創建指針p時刪除const(壞,我猜...)或者我必須添加一個const成員函數Execute()到ICommand。經過一段時間的努力之後,用戶必須實現兩個功能(更不用說發生了什麼,如果我們向基類添加一些其他純虛函數......),我想出了以下解決方案:
class ICommand
{
public:
virtual ~ICommand() {};
virtual int Execute()
{ //Scott Meyers way
return static_cast<const ICommand&>(*this).Execute();
}
virtual int Execute() const = 0;
protected:
ICommand() {};
};//class ICommand
這似乎做的工作相當好,但我不知道這是否是一個合適的解決方案,我的問題。我不認爲這對用戶來說非常直觀,因爲他總是要實現純虛擬成員函數的const版本,而不是非常量成員函數。
我的實際問題是,是否有任何副作用,我可能沒有考慮過,或者如果有任何更好的解決方案,我可能已經監督到目前爲止。
在此先感謝, 勒內。
一般而言,你是對的。最好的方法是避免函數的非''const'版本。所以這個例子被選作只是'const'函數不夠的不幸情況。 – PiJ