I have a std::list container, holding shared pointers of say class A. I have another class, say B, that is derived from A.
I currently have code that does this to populate the container:
shared_ptr<B> b = shared_ptr<B>(new B);
container.push_back(b)
This works fine.
Question is, how can I retrieve the shared_ptr < B > that was initially pushed back to the container?
Doing the following
list<shared_ptr<A> >::iter anIter = myContainer.begin();
shared_ptr<B> aB = *(anIter);
do not compile. I get error
Cannot convert 'A * const' to 'B *'
Any tips?
答案 0 :(得分:8)
如果您知道自己已经检索到了B,正如您的问题所示,那么您可以使用 constructor :
dynamic_cast<>()
如果有疑问,您可以使用 static_pointer_cast<>()
。但与传统的 container.push_back(make_shared<A>());
for (auto i = container.begin(); i!=container.end(); i++) {
shared_ptr<B> spb = dynamic_pointer_cast<B>(*i);
if (spb)
spb->showb(); // at least one virtual function
else cout << "the pointer was not to a B";
}
一样,只有当您的类具有多态时才会起作用,即您至少有一个虚函数:
static_cast<>()
对于普通指针,原则类似于dynamic_cast<>()
和const_pointer_cast<>()
,请参阅dynamic_pointer_cast<>()
。顺便说一句,对于普通指针,还有一个const_cast<>()
,就像 view.backgroundColor = UIColor.colorWithPatternImage(UIImage(named: "background.jpg"))
一样。
答案 1 :(得分:7)
您可以使用std::dynamic_pointer_cast
。
你这样使用它:
std::shared_ptr<Base> basePtr;
std::shared_ptr<Derived> derivedPtr = std::dynamic_pointer_cast<Derived>(basePtr);