【发布时间】:2011-10-10 09:44:20
【问题描述】:
我有一个基本多态类(带有虚拟方法)和一个派生自它。 我正在尝试使用以下代码
boost::shared_ptr<base_class> ptr( new derived_class() );
但编译器返回以下错误
cannot convert ‘fpga_northwest*’ to ‘fpga*’ in initialization
make: *** [../obj/ixecute_cmd_interface.o] Error 1
环顾四周,我很想使用以下构建好的,但我有一些疑问。你觉得对吗?
boost::shared_ptr<base_class> ptr_base;
boost::shared_ptr<derived_class> ptr_derived( new derived_class() );
ptr_base = boost::dynamic_pointer_cast<base_class>( ptr_derived );
如果我使用boost::static_pointer_cast,我会遇到编译器错误;因为我是从派生到基础的,所以static_cast 不应该更正确?
感谢您的帮助
【问题讨论】:
-
试试
dynamic_cast<base_class>(deriver_class object) -
不明白,这似乎工作正常:ideone.com/N63Qf
-
嗯,this example 工作正常。你的代码有什么不同?
-
@Nim:当您使用私有继承时,您的示例无法编译。也许这就是 OP 做错了什么?
-
@Bjorn,这将报告一个不同的错误 AFAIK(类似于无法访问的基地......等等)。我认为任何演员也不会对此有所帮助..
标签: c++ casting shared-ptr