C++11 智能指针和多态性

2022-01-24 00:00:00 polymorphism c++ smart-pointers

我正在使用 c++11 智能指针重写应用程序.

I'm rewriting an application using c++11 smart pointers.

我有一个基类:

class A {};

还有一个派生类:

class B : public A {
  public:
  int b;
};

我有另一个类包含带有 A 或 B 对象的向量:

I have another class containing a vector with either A or B objects:

class C {
  public:
  vector<shared_ptr<A>> v;
};

用 A(基类)对象构造 C 没有问题,但是如何用 B(派生类)对象填充它?

I have no problem constructing C with A (base class) objects but how can I fill it with B (derived class) objects?

我正在尝试这个:

for(int i = 0; i < 10; i++) {
    v.push_back(make_shared<B>());
    v.back()->b = 1;
};  

编译器返回:错误:A 类"没有名为b"的成员

And the compiler returns: error: ‘class A’ has no member named ‘b’

推荐答案

但是如何用 B(派生类)对象填充它?

But how can I fill it with B (derived class) objects?

您正在用(指向)B 对象的(指针)填充它.但是,指针的静态类型是指基类 A,因此您不能直接使用它们来访问派生类的任何成员.

You are filling it with (pointers to) B objects. However, the pointers' static type refers to the base class A, so you cannot directly use these to access any members of the derived class.

在您的简单示例中,您可以简单地保持指向 B 的指针并使用它:

In your simple example, you could simply keep hold of a pointer to B and use that:

std::shared_ptr<B> b = make_shared<B>();
b->b = 1;
v.push_back(b);

如果您无法访问原始指针,那么您将需要某种多态性:

If you don't have access to the original pointer, then you will need some kind of polymorphism:

  • 使用 static_cast<B*>(v.back().get()) 如果你知道所有对象都有类型 B
  • 如果对象可能有不同的类型,请使用虚函数或 dynamic_cast(需要基类包含虚函数才能工作)
  • use static_cast<B*>(v.back().get()) if you know that all objects have type B
  • use a virtual function or dynamic_cast (which requires the base class to contain a virtual function to work) if the objects might have different types

相关文章