简体   繁体   English

C ++ 11智能指针和多态

[英]C++11 smart pointers and polymorphism

I'm rewriting an application using c++11 smart pointers. 我正在使用c ++ 11智能指针重写应用程序。

I have a base class: 我有一个基类:

class A {};

And a derived class: 和派生类:

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

I have another class containing a vector with either A or B objects: 我还有一个包含带有A或B对象的向量的类:

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

I have no problem constructing C with A (base class) objects but how can I fill it with B (derived class) objects? 我用A(基类)对象构造C没问题,但是如何用B(派生类)对象填充C?

I'm trying this: 我正在尝试:

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

And the compiler returns: error: 'class A' has no member named 'b' 然后编译器返回:错误:“类A”没有名为“ b”的成员

But how can I fill it with B (derived class) objects? 但是如何用B(派生类)对象填充它?

You are filling it with (pointers to) B objects. 您正在用B对象填充(指向)。 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. 但是,指针的静态类型引用基类A ,因此您不能直接使用它们访问派生类的任何成员。

In your simple example, you could simply keep hold of a pointer to B and use that: 在您的简单示例中,您可以简单地持有指向B的指针并使用该指针:

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: 如果您无权访问原始指针,那么您将需要某种多态性:

  • use static_cast<B*>(v.back().get()) if you know that all objects have type B 使用static_cast<B*>(v.back().get()) ,如果你知道所有的对象都具有类型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 如果对象可能具有不同的类型,则使用虚拟函数或dynamic_cast (要求基类包含虚拟函数才能工作)
for(int i = 0; i < 10; i++) {
    auto bptr = make_shared<B>();
    v.push_back(bptr);
    bptr->b = 1;
};  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM