我声明了基类的二维动态数组。其中一些动态对象正在被声明为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++程序员从长远来看变得更加轻松愉快。 –