2015-04-17 56 views
2

我聲明瞭基類的二維動態數組。其中一些動態對象正在被聲明爲Derived類的對象。派生類的構造函數被調用,但派生類的對象不調用正確的虛擬功能基類和派生類的二維動態數組

有機體是Base類 螞蟻派生類

Organism.cpp

Organism::Organism(){//default constructor 
    occupy = false; 
    mark = '_'; 
} 
Organism::Organism(int){//constructor called on by the Ant constructor 
    occupy = true; 
} 
char Organism::getMark(){//Used to make sure the Ant constructor is properly called 
    return mark; 
} 
virtual void yell(){//virtual function 
     cout << "organism" << endl; 
    } 

Ants.cpp

Ant::Ant() : Organism(){}//not really used 
Ant::Ant(int) : Organism(5){//initialize the Ant object 
    setMark('O');//mark 
    antsNum++; 
} 
void yell(){//override the virtual function 
     cout << "ant" << endl; 
    } 

的main.cpp

Organism **grid = new Organism*[20]; 
char c; 
    ifstream input("data.txt");//file contains data 

    for (int i = 0; i < 20; i++){ 

     grid[i] = new Organism[20];//initialize the 2d array 

     for (int j = 0; j < 20; j++){ 
      input >> c;//the file has *, X, O as marks 

      if (c == '*'){ 
       grid[i][j] = Organism();//call on the default constructor to mark it as _ 
      } 
      else if (c == 'X'){ 
       grid[i][j] = Doodle(5); 
      } 
      else if (c == 'O'){ 
       grid[i][j] = Ant(5); 
      } 
     } 
    } 
//out of the loop 

cout << grid[1][0].getMark() << endl;//outputs 'O', meaning it called on the ant constructor 
    grid[1][0].yell();//outputs organism, it is not calling on the Ant definition of the function yell() 

我明白,所有的數組是類型有機體,而不是類型螞蟻,我該如何改變?

+3

有一個*指針矩陣*到基類型?是否有你不使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)的原因? –

+0

我真的不喜歡矢量,然後我必須使用其他功能,將不得不移動,摧毀和滋生其他物體。我猜想以後會嘗試向量。 –

+0

使用[C++標準庫](http://en.cppreference.com/w/cpp),包括其[containers](http://en.cppreference.com/w/cpp/container)和[算法] (http://en.cppreference.com/w/cpp/algorithm)將使您的C++程序員從長遠來看變得更加輕鬆愉快。 –

回答

1

您需要聲明的數組的指針的指針的指針:

Organism ***grid = new Organism**[20]; 

矩陣現在持有指針有機體。你做這件事的方式是用Doodle初始化生物體,而不是讓生物體成爲塗鴉。

你應該有:

grid[i][j] = new Doodle(5); 

眼下正在發生的事情是生物體拷貝構造函數被調用,所以你實際上是存儲生物,而不是指向派生類型。

做的更好的方法是使用boost ::矩陣:

boost::matrix<Organism *> m(20, 20); 
+0

'std :: vector >> grid'更好。 – Jarod42

+0

@ Jarod42有點。嵌套的'std :: vectors'仍然不是一個好的解決方案。 – Quentin

+0

取決於什麼。我不喜歡使用矢量來表示矩陣,因爲沒有人保證所有矢量的長度相同。也許使用boost :: matrix –

1

你有object slicing這裏。

有二十Organisms創建:

grid[i] = new Organism[20];//initialize the 2d array 

,然後嘗試在[i][j]到一個臨時Ant複製到Organism

grid[i][j] = Ant(5); 

但這不起作用。

刪除第一行(初始化。),並用

grid[i][j] = new Ant(5); 

並且同樣爲OrganismDoodle替換第二行。