2010-10-03 58 views
2

我在基類構造函數中有一個邏輯。邏輯的結果必須在派生類的構造函數中捕獲一個臨時變量。有沒有辦法做到這一點?基類構造函數中的C++引用

例如

class Base 
{ 
    Base() { int temp_value = some_logic; } 
}; 

class Derived : public Base 
{ 
    Derived() { // need the temp value here.. } 
}; 

謝謝, 戈庫爾。

+1

你有沒有考慮過讓'temp_value'成爲類的受保護成員,以便派生類的構造函數可以訪問它? – 2010-10-03 15:41:25

+0

@Richard ::添加一個成員變量不是一個選項,因爲這會增加對象的大小。相反,我們可以選擇重新計算值 – Gokul 2010-10-03 15:42:50

回答

2

我想我能想到的最簡單的方法是隻單獨some_logic到它自己的方法......

class Base 
{ 
    Base() { int temp_value = initializationLogic(); } 
    int initializationLogic(){ return some-logic;} 
}; 

class Derived : public Base 
{ 
    Derived() { int temp_value_here_too = initializationLogic(); } 
}; 
+0

結果將是initialLogic()被調用兩次。 – ChrisW 2010-10-03 15:47:18

+0

感謝您的回答。那麼如果我被誤解了,我並沒有要求代碼組織。我正在尋求避免雙重計算的方法。 – Gokul 2010-10-03 15:47:23

+1

但是你拒絕了*的方式,以避免雙重計算,當你說你不想添加一個字段的類。存儲值*是避免雙重計算的方法。 – 2010-10-03 15:51:46

2

或者:

class Base 
{ 
    protected int not_so_temp_value; 
    Base() { not_so_temp_value = some_logic_result; } 
}; 

class Derived : public Base 
{ 
    Derived() { // read the not_so_temp_value member here.. } 
}; 

或者:

class Base 
{ 
    Base(int some_logic_result) { int temp_value = some_logic; } 
}; 

class Derived : public Base 
{ 
    static Derived* create() 
    { 
     int some_logic_result = some_logic; 
     return new Derived(some_logic_result); 
    } 
    Derived(int some_logic_result) : Base(some_logic_result) 
    { // use the some_logic_result here.. } 
}; 
+0

!!感謝您的回覆。第一個增加的大小。第二個要求改變構造函數。哦耶!!!我可以將額外的一個作爲默認參數。謝謝..... – Gokul 2010-10-03 15:50:48

0

這是我打算使用的那個

class Base 
{ 
    Base(int& some_logic_result) { some_logic_result = some_logic; } 
}; 

class Derived : public Base 
{ 
    Derived(int some_logic_result = 0) : Base(some_logic_result) 
    { // use the some_logic_result here.. } 
}; 

謝謝, Gokul。