2010-11-11 100 views
0

我有一個棘手的問題,「覆蓋」靜態數組。我有靜態數組(爲簡單起見),它們在不同的派生類中具有固定長度,但仍然在編譯時知道所有大小。我也在基類中得到了一個虛函數,但我不知道如何解決在派生類中重寫這些數組和數組大小的問題,以便這個虛函數可以正常工作,即給出大小和數組來自派生類的內容。例如:覆蓋靜態成員和「靜態靜態數組」

class B { 
private: 
// these two are not really meaningful in this class (ABC) 
static const int n = 1; 
static double da[n]; 
public: 

virtual void f() 
{ 
    for(int i = 0; i < n; ++i) 
    { 
    // do something with n and da 
    std::cout << n << std::endl; 
    } 
} 
}; 

class D1 : public B { 
private: 
// these are subclass-specific (i.e. n might also change) 
static const int n = 4; 
static double da[n]; 
}; 

class D2 : public B { 
private: 
// these are subclass-specific (i.e. n might also change) 
static const int n = 6; 
static double da[n]; 
}; 


double D1::da[] = {1., 2., 3., 4.}; 
// ... 

int main() 
{ 
B *p = new D; 
p->f(); // I'd like to see 4 instead of 1 
} 

你可以建議修補程序或正確地這樣做的不同的方式?我認爲std :: vector會做到這一點(?),但需要很多工作來適應我現有的代碼。 非常感謝, 彼得

回答

1

由於f只在基類中定義,它將使用該類'n變量。

也許移動:

for(int i = 0; i < n; ++i) 
    { 
    // do something with n and da 
    std::cout << n << std::endl; 
    } 

爲一個單獨的函數,而是有它讓你在什麼「n」是通過。像

void doStuff(int num) { 
    for(int i = 0; i < num; ++i) 
    { 
     // do something with n and da 
     std::cout << num << std::endl; 
    } 
} 

,並讓每個子類中實現f()的調用doStuff(n),其中n將被各班自己的N個變量。

1

您可以使用Curiously Recurring Template Pattern來讓您的函數訪問派生類最多的靜態數組。

+0

非常感謝,我按照您的建議嘗試過,並按預期工作。不幸的是,我想能夠在B接口上使用動態多態性,我認爲這是不可能的。或者是? – Peter 2010-11-13 22:14:57