2015-04-17 35 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替换第二行。