C++继承和共享指针

2022-07-19 00:00:00 inheritance c++ shared-ptr

情况是这样的。假设我们有一个虚拟基类(例如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();
}

相关文章