我可以从一个类的多个对象的列表得到一些东西
Can i get something from a list with multiple objects of a class?
我有:
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
部分。
如果你想多态存储 Publication
s,你需要使用指针或引用。我建议使用以下方式之一:
// 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;
};
相关文章:
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 从封装在对象中的函数 C++ 返回时为空的列表
- 如何在不销毁对象的情况下返回对象列表
- 如何使用Q_PROPERTY公开自定义对象列表
- 链接列表在 cpp 中包含不同的对象类
- 如何使用对象制作分数列表并获得平均值
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 如何在Windows Media Foundation SDK中指定语言列表对象
- 在 DLL 中嵌入 Python:Py_DECREF列表对象时访问冲突读取位置
- 将类的每个实例添加到列表对象的构造函数
- 列表<对象*>迭代器中的分段错误
- 如何使用list::sort()对STL列表对象进行排序,同时将自定义排序函数作为参数传递给list::排序
- 如何防止客户端修改列表对象
- c++列表对象错误
- 在列表对象中使用对象的派生函数
- 编译器错误 使用列表<对象*的迭代器> C++