我可以从一个类的多个对象的列表得到一些东西

Can i get something from a list with multiple objects of a class?

本文关键字:列表 对象 一个 我可以      更新时间:2023-10-16

我有:

class Library
{
private:
list<Publication> L;
}
class Publication
{
protected:
string title;
string editor;
}
class Book:public Publication
{
private:
vector<string> Author;
}

当我插入一本书在我的列表,我失去了作者?如果不是,当我想从列表中显示一个出版物时,我还想显示该出版物的作者。我如何在不修改列表结构的情况下做到这一点?

如果不改变L的类型,就无法做到这一点。它是list<Publication>,它储存的是Publication,而不是Book。如果你把Book推进去,它会被切成薄片,只留下Publication部分。

如果你想多态存储 Publications,你需要使用指针或引用。我建议使用以下方式之一:

// When the Library has sole-ownership of a dynamically allocated Publication:
std::list<std::unique_ptr<Publication>> L;
// When the Library has shared-ownership of a dynamically allocated Publication:
std::list<std::shared_ptr<Publication>> L;
// When the Library wants a reference to a Publication:
std::list<std::reference_wrapper<Publication>> L;

如果由于某种原因你不能使用这些,你当然可以在L中存储原始指针。

您正在存储Publication对象,因此当您尝试存储Books时,您将获得对象切片。解决方案是将智能指针存储到Publications。例如,

#include <memory>
class Library
{
private:
  std::list<std::unique_ptr<Publication>> L;
};