C++继承和共享指针 [英] c++ Inheritance and shared pointers
本文介绍了C++继承和共享指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
情况是这样的。假设我们有一个虚拟基类(例如ShapeJuggler
),它包含一个方法,该方法将指向虚拟基类对象的共享指针(例如Shape
)作为参数。让我们跳到下面的伪代码来理解:
class Shape {
}
class ShapeJuggler {
virtual void juggle(shared_ptr<Shape>) = 0;
}
// Now deriving a class from it
class Square : public Shape {
}
class SquareJuggler : public ShapeJuggler {
public:
void juggle(shared_ptr<Shape>) {
// Want to do something specific with a 'Square'
// Or transform the 'shared_ptr<Shape>' into a 'shared_ptr<Square>'
}
}
// Calling the juggle method
void main(void) {
shared_ptr<Square> square_ptr = (shared_ptr<Square>) new Square();
SquareJuggler squareJuggler;
squareJuggler.juggle(square_ptr); // how to access 'Square'-specific members?
}
Make_Shared或Dynamic/Static_cast似乎不能完成这项工作。
这有可能吗?有什么想法、建议吗?
谢谢
推荐答案
这是std::dynamic_pointer_cast
(或其朋友之一)发挥作用的地方。
与dynamic_cast
类似,但对于std::shared_ptr
。
在您的情况下(假设Shape
类是多态的,因此dynamic_cast
工作):
void juggle(shared_ptr<Shape> shape) {
auto const sq = std::dynamic_pointer_cast<Square>(shape);
assert(sq);
sq->squareSpecificStuff();
}
这篇关于C++继承和共享指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文