[英]How to share same data between multiple instances at inheritance levels?
我想實例化具有相同繼承級別的多個對象,並為每個級別使用相同的數據。 因此,我考慮了類的繼承和靜態成員。
這是我的嘗試 :
#include <iostream>
class Father
{
public:
static int sValue;
inline int GetValue() { return sValue * 10; }
};
class Child1 : public Father
{
public:
};
class Child2 : public Father
{
public:
};
int Father::sValue = 0;
int main()
{
Child1 child1_1;
Child1 child1_2;
Child2 child2_1;
Child2 child2_2;
child1_1.sValue = 1;
child2_1.sValue = 2;
std::cout << child1_2.GetValue() << std::endl;
std::cout << child2_2.GetValue() << std::endl;
}
在我的例子都Child1
情況下應該返回10 GetValue()
兩者Child2
的實例應該使用返回20 GetValue()
由於功能相同,所以我不想為每個孩子覆蓋它(這就是為什么我將其放置在Father
中的原因)。
問題在於, Child1
實例也返回20調用GetValue()
。
因此, static
是在“主要”父母而非孩子之間共享的。
由於該sValue
值用於GetValue()
,因此將其正確放置在此處是正確的。 但是我不能這樣分離靜態/相同數據。
你會怎么做?
splrs用戶已正確識別您的問題,解決方案是正確的。 您需要具有兩個不同靜態對象的兩個不同功能。 您可以通過使用模板來避免重復代碼:
template<class Child>
struct Father {
static int sValue;
int GetValue() { /* ... */ }
};
struct Child1 : Father<Child1> {};
struct Child2 : Father<Child2> {};
這個成語被稱為好奇重復模板模式 。
當然,現在沒有共同的父母了。 如果需要,可以從非模板庫繼承模板:
struct FatherBase {};
template<class Child>
struct Father : FatherBase { /*...*/ };
並且,如果您需要從基礎訪問GetValue
的不同版本,則需要一個虛函數:
struct FatherBase {
virtual int GetValue() = 0;
};
template<class Child>
struct Father : FatherBase {
// ...
int GetValue() override { /* ... */ }
};
您在調用child1_1.sValue = 1;
時正在修改Father::sValue
child1_1.sValue = 1;
和child2_1.sValue = 2;
有一個實例屬於Father
,因此無論您如何訪問它(通過針對類或實例的方法),都可以在調用GetValue()
之前獲得設置的任何內容。
如果你想有一個Child1
和Child2
的版本,則靜態成員和方法添加到這些類。
我認為以下可能是您追求的目標:
class Father
{
public:
inline int GetValue() { return DoGetValue() * 10; }
void SetValue( int value ) { DoSetValue( value ); }
protected:
virtual int DoGetValue() = 0;
virtual void DoSetValue( int value ) = 0;
};
class Child1 : public Father
{
public:
static int sValue;
protected:
int DoGetValue() override { return sValue; }
void DoSetValue( int value ) override { sValue = value; }
};
class Child2 : public Father
{
public:
static int sValue;
protected:
int DoGetValue() override { return sValue; }
void DoSetValue( int value ) override { sValue = value; }
};
int Child1::sValue = 0;
int Child2::sValue = 0;
int main()
{
Child1 child1_1;
Child1 child1_2;
Child2 child2_1;
Child2 child2_2;
child1_1.SetValue( 1 );
child2_1.SetValue( 2 );
std::cout << child1_2.GetValue() << std::endl;
std::cout << child2_2.GetValue() << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.