gpt4 book ai didi

c++ - boost::shared_ptr 和动态转换

转载 作者:IT老高 更新时间:2023-10-28 22:26:15 40 4
gpt4 key购买 nike

我在使用基类的 shared_ptr 时遇到问题,我似乎无法在取消引用派生类的方法时调用它。我相信代码会比我更冗长:

class Base : public boost::enable_shared_from_this<Base>
{
public:
typedef boost::shared_ptr<BabelNet> pointer;
};

class Derived : public Base
{
public:
static pointer create()
{
return pointer(new Derived);
}
void anyMethod()
{
Base::pointer foo = Derived::create();
// I can't call any method of Derived with foo
// How can I manage to do this ?
// is dynamic_cast a valid answer ?
foo->derivedMethod(); // -> compilation fail
}

};

最佳答案

static_cast with boost::shared_ptr?

您需要使用 dynamic_pointer_cast获得适当的 shared_ptr 实例化。 (对应一个dynamic_cast)

关于c++ - boost::shared_ptr 和动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4277810/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com