Base和Derived类的二维动态数组

时间:2015-04-17 12:21:24

标签: c++

我宣布了Base类的2-D动态数组。其中一些动态对象被声明为Derived类的对象。正在调用Derived类的构造函数,但Derived类的对象没有调用正确的虚函数

有机体是基类 Ant是派生类

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()

我明白所有数组都是有机体类型,而不是Ant类型,我该如何更改?

2 个答案:

答案 0 :(得分:1)

您需要将数组声明为指向指针的指针:

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

矩阵现在指向有机体。你这样做的方式是用涂鸦初始化有机体,而不是让有机体成为涂鸦。

你应该:

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

现在正在发生的事情是正在调用有机体复制构造函数,因此您实际上存储了有机体而不是指向派生类型的指针。

更好的方法是使用boost :: matrix:

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

答案 1 :(得分:1)

这里有object slicing

创建了二十Organisms个:

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

然后,您尝试将Ant临时Organism复制到[i][j]

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

但这不起作用。

删除第一行(初始化..),并用

替换第二行
grid[i][j] = new Ant(5);

同样适用于OrganismDoodle