[英]C++ Constructors, Constants, Inheritance and Avoiding Repetition
所以我已經學習C ++幾周了,但是我有點麻煩:
Class Tool
{
public:
Tool(const float maxCarried = 1):maxAmountCarried(maxCarried){}
virtual void Use() = 0;
/* ... */
}
Class CuttingTool: public Tool
{
public:
CuttingTool(const float maxCarried):Tool(maxCarried){}
virtual void Use(){ /* ... */ }
/* ... */
}
Class Saw: public CuttingTool
{
public:
Saw(const float maxCarried):CuttingTool(1){}
virtual void Use(){ /* ... */ }
/* ... */
}
Class Scissors: public Fruit
{
public:
Scissors(const float maxCarried):CuttingTool(2){}
virtual void Use(){ /* ... */ }
/* ... */
}
注意事項:
問題在於我必須繼續寫:
ClassName(const float maxCarried):BaseClass(maxCarried){}
而且,這真的很乏味,我擔心如果我要添加一個新的const值,我將不得不再次重復該過程(當您有50個繼承自Food:S的類時會出現問題)。
我覺得我的設計似乎很差。 有沒有一種方法可以避免一遍又一遍地重復同一行代碼,還是我只需要吸收它並加以處理?
提前致謝。
如果您唯一關心的是重復的初始化列表,則可以使用如下宏:
#define DEFAULT_CONSTRUCTOR(Child, Parent) Child(float max) : Parent(max) {}
並像這樣使用它:
class Saw : public CuttingTool
{
public:
DEFAULT_CONSTRUCTOR(Saw, CuttingTool) {}
};
您可以擴展這個想法並執行類似的操作:
#define BEGIN_CLASS(Child, Parent) class Child : public Parent { \
public: \
Child(float max) : Parent(max) {}
#define END_CLASS };
並聲明您的課程:
BEGIN_CLASS(Scissors, Tool)
void cut_through_paper() {} // specific method for scissors
END_CLASS
請注意,將const float
用作參數毫無意義,因為無論如何您都無法更改通過值傳遞的參數。 但是,您可能想使用const float&
通過引用傳遞參數,如果float的大小大於特定平台中指針的大小,這將是有意義的。
如果您從未更改最大值,則可以將其設為靜態並在所有工具實例之間共享:
class Tool
{
protected:
static const float _max;
public:
Tool() {}
};
const float Tool::_max = 0;
如果您只想更改一次最大值(例如在程序開始時,則可以添加一個靜態函數:
static void globalMax(float max) { Tool::_max = max; }
並在適當的地方使用它:
int main() {
Tool::globalMax(5);
...
...
}
請注意,您應該從_max
聲明中刪除const
。
最后,如果性能是一個問題,那么您可能需要重新考慮您的設計,並可能選擇其他東西(也許是模板?)
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.