【发布时间】:2022-01-15 17:44:34
【问题描述】:
所以我有一个包含一个基类和两个派生类的简单代码。每个派生类都有自己的变量,基类有一个 id 变量,应该与我从派生类创建的所有元素共享。
创建 2 个对象并将它们添加到向量中后,我只能打印它们的 ID。有什么方法可以从相应的元素中获取 a 和 b 变量? (例如:std::cout << items[0]->a;)
class Item
{
public:
int id;
Item(int id) { this->id = id; }
};
class ItemTypeA : public Item
{
public:
int a;
ItemTypeA(int a, int id) : Item(id) { this->a = a; }
};
class ItemTypeB : public Item
{
public:
int b;
ItemTypeB(int b, int id) : Item(id) { this->b = b; }
};
int main()
{
std::vector<std::shared_ptr<Item>> items;
items.push_back(std::make_unique<ItemTypeA>(2, 0));
items.push_back(std::make_unique<ItemTypeB>(3, 1));
std::cout << items[0]->// I wanna print the a variable but it only lets me print the ID;
return 0;
}
【问题讨论】:
标签: c++ class constructor derived-class