【发布时间】:2021-05-20 03:42:58
【问题描述】:
所以我有一个名为 items 的基类,从名为 consumable 和设备的项目中继承的 2 个类,以及从它们中的每一个继承的 2 个以上的类。每个都有 toString() 函数,随着你沿着继承的列表向下走,它就会建立起来。但这是我的问题。我需要通过指针将从消耗品和设备继承的 4 个对象放入一个项目数组中。我该怎么做?
我的主目录中目前有这段代码:
Weapon greatSword("Great Sword", "A sword forged for mighty warriors", 12.50, true, 1, 150.00f, false, 13, "Slashing");
Armor mekiChestplate("Meki's Chest Plate", "A chest plate given to me by my mother", 1500.25f, false, 25, 2000.50f, true, "Chest", 18);
Food pie("Grandma's Pie", "Baked with love and affection", 10.35f, true, 5, 150, 0);
Potion spiderVenom("Spider's Venom", "Poision picked up from a spider", 100.55f, false, 10, 100, 1);
Item inventory[4]
{
greatSword,
mekiChestplate,
pie,
spiderVenom
};
for(int i = 0; i < 4; i++)
{
cout << inventory[i].toString() << endl;
cout << "-----------------------------------------------------------" << endl;
}
return 0;
这行得通,因为他们不调用自己的 toString,只调用 Item toString。如何将这 4 个项目放入一个指针数组中?
【问题讨论】:
-
最直接:
Item inventory[4]到Item* inventory[4],greatSword到&greatSword等。标准建议考虑使用std::vector<std::unique_ptr<Item>>或其他东西,而不是 C 样式数组和原始指针。 -
@NathanPierson 这行得通!谢谢,我一直忘记在项目中添加 &。如果你不介意我问,使用向量而不是原始指针有什么好处?
-
为什么
vector:它们可以调整大小而不是在编译时具有已知的固定容量,它们更容易复制并作为函数参数传递。为什么unique_ptr:更明确地说明变量的预期所有权和寿命,避免内存泄漏,迫使您更明确地了解预期的复制行为。