boost::shared_ptr 和动态转换
我在使用基类的 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
}
};
I have a problem using a shared_ptr
of a base class, I can't seem to be able to call the derived class's methods when dereferencing it. I believe code will be more verbose than me:
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
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅static_cast with boost::shared_ptr?
您需要使用dynamic_pointer_cast 获取适当的
shared_ptr
实例化。 (对应于dynamic_cast
)see static_cast with boost::shared_ptr?
you'll need to use dynamic_pointer_cast to get the appropriate
shared_ptr
instantiation. (corresponding to adynamic_cast
)无论是否共享指针,当您有一个指向
Base
的指针时,您只能从Base
调用成员函数。如果您确实需要
dynamic_cast
,则可以使用提升,但很可能你不应该这样做。相反,请考虑您的设计:Derived
是一个Base
,这是一种极其牢固的关系,因此请仔细考虑Base< /code> 接口以及是否确实必须知道具体类型。
Shared pointer or not, when you have a pointer to a
Base
, you can only call member functions fromBase
.If you really need to
dynamic_cast
, you can usedynamic_pointer_cast
from boost, but chances are that you shouldn't. Instead, think about your design :Derived
is aBase
, and this is an extremely strong relationship, so think carefully aboutBase
interface and if the concrete type really has to be known.如果派生方法没有在基类中声明(无论是否是虚拟的),那么编译失败是正常的。共享 ptr 知道并使用基类(通过它所持有的指针),并且对派生类及其具体方法一无所知。
If derivedMethod is not declared in base class (virtual or not), then it is normal that the compilation would fail. The shared ptr knows and uses the base class (through the pointer it holds), and knows nothing about the derived class and its specific methods.
即使使用原始指针,您的代码也无法工作。
即使在基类中,您也需要声明派生方法() 方法,或者拥有指向派生对象的指针。
Your code wouldn't work even with raw pointers.
You need either to declare
derivedMethod()
method even in base class or to have a pointer to aDerived
object.