2012-02-28 117 views
0

我是新來的C++中的多態。在我的構造函數中,我需要幾個對象並創建一個生物集合。當我更改一個對象時,它會更改所有相同的對象。我不知道爲什麼會發生這種情況。多態C++,當對一個對象進行更改時,所有對象都發生變化

在我的構造函數中。

lmaxSize=9; 
lmiddleSize=6; 
lsmallSize=3; 
int j=0; 
for(int i=0;i<lmaxSize;i++) 
{ 
    if(j=3) 
    { 
     j=0; 
    } 
    if(i<lsmallSize) 
    { 
     creature[i]=&dizzy[j]; 

    } 
    else if(i>=lsmallSize && i<lmiddleSize) 
    { 
     creature[i]= &pred[j]; 
    } 
    else 
    { 
     creature[i]=&agile[j]; 
    } 
    j++; 
} 

當我更改pred對象時,所有pred對象都會改變。例如,當我使用消耗能量時,它會改變所有預測對象的能量。不知道爲什麼

void collections::consumeEnergy() 
{ 
int creatureNum=0; 
cin>>creatureNum; 
creature[creatureNum]->consumeEnergyUnits(); 


    } 

predatorCreature

void predatorCreature::consumeEnergyUnits() 
    { 
     if (_consume < 10) 
     { 
      _energyUnits -= 2; 
      _energyLevel += 1; 
     } 
     else if (_consume <= 30) 
     { 
      _energyUnits -= 5; 
      _energyLevel += 2; 
     } 
     else 
     { 
      _energyUnits -= 7; 
      _energyLevel += 4; 
     } 
} 

agileCreature

void agileCreature::consumeEnergyUnits() 
{ 
     if (_consume < 10) 
     { 
      _energyUnits -= 2; 
      _energyLevel += 1; 
     } 
     else if (_consume <= 30) 
     { 
      _energyUnits -= 5; 
      _energyLevel += 2; 
     } 
     else 
     { 
      _energyUnits -= 7; 
      _energyLevel += 4; 
     } 
} 
+0

向我們展示您的類定義 – Sid 2012-02-28 21:27:40

+0

代碼中沒有足夠的'std :: unique_ptr'。 – 2012-02-28 21:31:48

回答

4
if(j=3) 

你可能想

if(j==3) 

表達式j=3將始終產生「真」,並且您將始終執行:j=0;,您稍後將從陣列中獲取相同的元素。 [總是每個數組中的第一個元素]。

我不確定它是否解決了這個問題 - 沒有更多的代碼是有點困難 - 但它很可能是一個問題。

+0

謝謝,就是這個問題 – Aaron 2012-02-28 21:31:27

+0

@Aaron:學習編譯時帶有警告(例如''-Wall'),不要忽略它們。在這種情況下,大多數編譯器會發出警告。 GCC和Clang就是這種情況。 – netcoder 2012-02-28 21:34:06

相關問題