c++ - 基类和派生类的二维动态数组

标签 c++

我正在声明基类的二维动态数组。其中一些动态对象被声明为派生类的对象。正在调用派生类的构造函数,但派生类的对象未调用正确的虚函数

有机体是基类 Ant是派生类

有机体.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;
    }

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

我确实知道所有数组都是 Organism 类型,而不是 Ant 类型,我该如何更改它?

最佳答案

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

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

矩阵现在保存指向有机体的指针。您这样做的方式是用 Doodle 初始化一个有机体,而不是让一个有机体成为一个 Doodle。

你应该有:

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

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

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

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

关于c++ - 基类和派生类的二维动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29699075/

相关文章:

c++ - Doxygen 报告 "potential recursive class relation"

java - 在不使用 matlab 头文件和库的情况下编写 MAT 文件

C++:变量与引用?

c++ - 在 C++ 中,template<> 是什么意思?

c++ - dynamic_cast 返回相同的对象类型失败,具有多重继承和中间变量

c++ - 创建与对话框一起工作的线程

c++ - 使用 C++ 模板定义函数,但显式删除它以防止误用

c++ - 按顺序移动数组中的元素

c++ - C 和 C++ 中的二维数组差异

c++ - 如何从头开始编写 std::floor 函数