[英]Static (single instance) Array For a Class C++
為了使事情盡可能簡單,我想用靜態數組構造一個類。 在程序的整個生命周期中一次聲明並在類的所有實例之間共享的數組。
作為上述問題的擴展,我想知道是否可以形成繼承層次結構,以使子代與父代具有不同的(靜態)數組。
最后,如果可能的話,我希望能夠在我的類的頭文件中聲明這些數組。
單獨來看,這些任務似乎很合理,但是結合起來,我對如何編寫此代碼絕對感到困惑,請多謝您提供的任何幫助。
編輯
在頭文件中:
class A {
public:
static int[] arr;
static int arrLength;
};
class B : A {
public:
static int[] arr = {1, 2, 3}
static int arrLength = 3;
};
其中,A僅用作層次結構的根,而其他無關屬性和功能則具有一定程度的多態性。
靜態數據成員不能被繼承,因此我看不到有任何通過普通子類化/繼承來做到這一點的機會。 您寧可對這種層次結構進行編碼,例如,通過引入一個以類名作為鍵的映射。
我通過濫用模板看到了一個(丑陋的)“解決方案”,它是如此丑陋,我想與您分享:-)。 它利用了以下事實:模板類在參數化/實例化后會針對不同類型產生不同的類。 這也適用於其靜態數據成員:
template<typename T = char[100]>
class MyClass {
public:
static T val;
};
template<typename T>
T MyClass<T>::val = "";
class Derived1 : public MyClass<char[101]> {
};
class Derived2 : public MyClass<char[102]> {
};
int main() {
Derived1 c1;
Derived2 c2;
Derived2 c2_2;
strcpy(c1.val, "Herbert");
strcpy(c2.val, "Anton");
cout << c1.val << " " << c2.val << " " << c2_2.val << endl;
}
輸出顯示Derived2
-instances共享一個公共值,而Derived1
-instances具有它們自己的值:
Herbert Anton Anton
明顯的缺點是您必須為每個子類引入不同的類型(即char[101], char[102],...
;否則它不會產生不同的類,並且您將再次共享一個公共的靜態變量。)
class Derived1 : public MyClass<char[101]> { ... }
class Derived2 : public MyClass<char[101]> { ... }
會產生輸出,使得即使Derived1
和Derived2
Derived1
也為靜態數據成員val
共享相同的值:
Anton Anton Anton
這就是為什么它不僅丑陋而且不切實際的原因。
如簡介中所述,使用“普通”繼承將無濟於事,因為靜態數據成員在某種程度上等效於相應類的命名空間中的“全局”變量。 因此它們不會被繼承,但是您必須為每個子類定義一個這樣的變量。 而且,由於對靜態數據成員沒有繼承,因此對它們沒有動態綁定:
class Base {
public:
static char v[100];
};
char Base::v[100];
class Derived_1 : public Base {
public:
static char v[100];
};
char Derived_1::v[100];
class Derived_2 : public Base {
public:
static char v[100];
};
char Derived_2::v[100];
int main() {
Derived_1 c1;
Derived_2 c2;
strcpy(Base::v, "Base");
strcpy(c1.v, "Herbert");
strcpy(c2.v, "Anton");
cout << c1.v << " " << c2.v << endl;
Base* b = &c2;
cout << b->v << endl;
return 0;
}
輸出:
Herbert Anton
Base
所以仍然不是您想要實現的目標; 這就是為什么我認為以類名作為鍵的映射仍然是一個更好的選擇。
如果對於派生類型確實需要不同的數組,建議使用虛擬生成器函數,該函數返回指向靜態函數本地數組的指針:
class Base
{
public:
virtual Base * get_array()
{
static Base * array[]{ ... };
return array;
}
};
class Derived1 : public Base
{
public:
Derived * get_array()
{
static Derived * array[]{ ... };
return array;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.