C ++ 11智能指针和多态 [英] C++11 smart pointers and polymorphism
问题描述
我正在使用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(派生类)对象填充C?
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 typeB
- 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
这篇关于C ++ 11智能指针和多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!