情况是这样的。假设我们有一个虚拟基类(例如 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
的地方(或其 friend 之一)开始发挥作用。
它就像 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++ 继承和共享指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42759612/