【发布时间】:2020-03-19 18:58:55
【问题描述】:
我有几个类继承自一个主类。为了简单起见,我过度简化了类定义以使其简短明了。
动物.h
所有其他类继承自的主类:
class Animal {
protected:
string name;
public:
Animal(string name);
virtual string toString() { return "I am an animal"; }
};
鸟.h
class Bird: public Animal {
private:
bool canFly;
public:
Bird(string name, bool canFly = true)
: Animal(name) // call the super class constructor with its parameter
{
this->canFly = canFly;
}
string toString() { return "I am a bird"; }
};
indect.h
class Insect: public Animal {
private:
int numberOfLegs;
public:
Insect(string name, int numberOfLegs) : Animal(name) {
this->numberOfLegs = numberOfLegs;
}
string toString() { return "I am an insect."; }
};
现在,我需要声明一个vector<Animal>,它将包含每个继承类的多个实例。
main.cpp
#include <iostream>
#include "animal.h"
#include "bird.h"
#include "insect.h"
// assume that I handled the issue of preventing including a file more than once
// using #ifndef #define and #endif in each header file.
int main() {
vector<Animal> creatures;
creatures.push_back(Bird("duck", true));
creatures.push_back(Bird("penguin", false));
creatures.push_back(Insect("spider", 8));
creatures.push_back(Insect("centipede",44));
// now iterate through the creatures and call their toString()
for(int i=0; i<creatures.size(); i++) {
cout << creatures[i].toString() << endl;
}
}
我希望得到以下输出:
我是一只鸟
我是一只鸟
我是昆虫
我是昆虫
但我得到了:
我是动物
我是动物
我是动物
我是动物
我知道这与“矢量生物;. It is calling the constructor for Animal. But my intention is to tell the compiler, that this creaturespoints to an array ofAnimalinherited classes, might beBirdmight beinsect, the point is: they all implement their own unique respective version of toString()` 行有关。
如何声明从同一祖先继承的对象的多态数组?
【问题讨论】:
-
你面临的是对象切片问题
-
@ThePhilomath 你愿意详细说明一下,还是指出我可以在哪里解决这个问题?
-
问题在于
creatures.push_back(Bird("duck", true));您正在创建一个 Bird 对象并将其复制到 Animal 对象中。一种方法是动态创建对象,以便可以使用 vtable 解析正确的函数调用 -
创建一个指向 Animal 的指针向量:
vector<Animal*>
标签: c++ inheritance vector polymorphism