我聲明瞭基類的二維動態數組。其中一些動態對象正在被聲明爲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()
我明白,所有的數組是類型有機體,而不是類型螞蟻,我該如何改變?
有一個*指針矩陣*到基類型?是否有你不使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)的原因? –
我真的不喜歡矢量,然後我必須使用其他功能,將不得不移動,摧毀和滋生其他物體。我猜想以後會嘗試向量。 –
使用[C++標準庫](http://en.cppreference.com/w/cpp),包括其[containers](http://en.cppreference.com/w/cpp/container)和[算法] (http://en.cppreference.com/w/cpp/algorithm)將使您的C++程序員從長遠來看變得更加輕鬆愉快。 –