有 3 个这样的类:
class Item {
public:
std::string text;
};
class Item1 : Item {
public:
int number1;
Item1() {
this->text = "123";
this->number1 = 0;
}
};
class Item2 : Item {
public:
unsigned int number2;
Item2() {
this->text = "321";
this->number2 = 1000;
}
};
问题是这样的:
std::vector<Item*> map = {};
Item1* i1 = new Item1();
Item2* i2 = new Item2();
map.push_back( i1, i2 );
不可能以这种方式存储指向子类对象的指针,我已经阅读了该问题的解决方案,理论上它应该可行,也许我不明白什么或者我误解了?
map[0]->number1
如果这个问题可以解决,那么下一个问题就会出现,如果map[1]->number1
Item 类型中不存在这些字段,我该如何获取它们
。我恳请你帮我解决这个问题
PS 标准 c++17