[英]How can I have a list of base class objects and access derived class fields?
Let's say I have a base class and two derived classes:假设我有一个基类 class 和两个派生类:
class a {};
class b : a { int a; };
class c : a { int b; };
And I have a list of the base class, and I insert the derived class into the list:我有一个基数 class 的列表,我将派生的 class 插入到列表中:
std::list<a> list;
list.emplace_back(b());
list.emplace_back(c());
Now, I want to access int a
like this:现在,我想像这样访问int a
:
for(auto i : list)
{
i.a = 5;
}
I already have checks in place to see what class it is, but the compiler is still not letting me access it.我已经检查过它是什么 class,但编译器仍然不允许我访问它。
How can I access any field in the derived class from the base class?如何从基数 class 访问派生的 class 中的任何字段?
This question has been asked many times, but none of the methods have worked for me so far.这个问题已被问过很多次,但到目前为止,没有一种方法对我有用。
First, you need a list of base class pointers , otherwise you will slice the objects when you insert them into the list.首先,您需要一个基数为 class 的指针列表,否则当您将对象插入列表时,您将对对象进行切片。
Then, you need to type-cast the pointers to access derived classes as needed.然后,您需要对指针进行类型转换以根据需要访问派生类。
If all of the list elements are pointing at the same derived type, you can use static_cast
:如果所有列表元素都指向相同的派生类型,您可以使用static_cast
:
struct A {};
struct B : A { int a; };
struct C : A { int b; };
std::list<std::unique_ptr<A>> lst;
lst.push_back(std::make_unique<B>());
lst.push_back(std::make_unique<B>());
for(auto &ptr : lst)
{
static_cast<B*>(ptr.get())->a = 5;
}
Otherwise, use dynamic_cast
instead to test the derived class type before accessing its fields:否则,在访问其字段之前使用dynamic_cast
来测试派生的 class 类型:
struct A {};
struct B : A { int a; };
struct C : A { int b; };
std::list<std::unique_ptr<A>> lst;
lst.push_back(std::make_unique<B>());
lst.push_back(std::make_unique<C>());
for(auto &ptr : lst)
{
B *b = dynamic_cast<B*>(ptr.get());
if (b)
b->a = 5;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.