c++ 继承和共享指针

标签 c++ inheritance 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的地方(或其 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/

相关文章:

c++ - 尝试构建 makefile 时无法识别文件格式

c# - 在 C# 中访问泛型类的静态方法

inheritance - 用例中的扩展与泛化

c++ - shared_ptr 类 vector 的 vector 初始化问题

java - Google Protocol 重复值的结构是怎样的?它们的局限性和优势是什么?

C++ 每次将 String 转换为 int 一个字符

c++ - 号码分割

C++:多重继承中类对象的意外大小

c++ - 从技术角度来看,为什么 shared_from_this 不能在构造函数中使用?

c++ - 在空指针的情况下,shared_ptr 和 unique_ptr 的删除器的标准行为是否不同?