我有一個類參數,其目的是爲了表示某個參數可以容納的可能值(實現兩個關鍵方法,GetNumValues()和GetValue(int index))。撰寫您繼承的類的對象?
通常一個邏輯參數(參數值是位標誌)最好由2個或更多的Parameter類實例表示(即參數可以是1或2,參數可以是4或8,而不是一個參數可以是5,6,9或10)。爲了處理這個問題,我想創建一個包含Parameters的CompositeParameter類,並且將基於它所包含的參數的組合實現GetNumValues()和GetValue()函數。
而且由於CompositeParameter組合參數使它們充當單個參數,所以「CompositeParameter是參數」關係是合理的。所以我發現自己處於這樣一種情況,即我有一個類組成它繼承的類的對象,這看起來不正確。但同時,我不明白爲什麼更高級別的代碼不應該能夠將CompositeParameters和Parameters完全相同。
我能想到的唯一選擇是讓CompositeParameter簡單地組成參數,而更高級別的代碼只會處理CompositeParameters。然而,這是有點浪費的B/C一般情況下將是僅包含一個參數的CompositeParameters。
想法?
class Parameter
{
public:
virtual unsigned int GetNumValues() const {...}
virtual unsigned int GetValue(unsigned int index) const {...}
}
class CompositeParameter : public Parameter
{
public:
// product of GetNumValues() of each item in mParamList
virtual unsigned int GetNumValues() const {...}
// allow all the possible combinations of the items in mParamList to be
// treated as one parameter. i.e. if mNumParams = 2, this would be analogous
// to getting the row and col index of a matrix from index, and combining
// the mParamList[0]->GetValue(row) and mParamList[1]->GetValue(col)
virtual unsigned int GetValue(unsigned int index) const {...}
private:
static const unsigned int MAX_PARAMS = 10;
unsigned int mNumParams;
const Parameter* mParamList[MAX_PARAMS];
}
在談論C++代碼時,使用C++代碼而不是英語來描述問題幾乎總是比較好的。 – 2010-02-03 23:12:45