基类的shared_pointer不能使用多态派生创建
我有一个基本多态类(带有虚拟方法)和一个派生自它的类。 我正在尝试使用以下代码
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
不应该更正确吗?
感谢您的帮助
I have a base polymorphic class ( with virtual methods ) and a derived from it.
I am trying to use the following code
boost::shared_ptr<base_class> ptr( new derived_class() );
but the compiler returns me the following error
cannot convert ‘fpga_northwest*’ to ‘fpga*’ in initialization
make: *** [../obj/ixecute_cmd_interface.o] Error 1
Reading a look around I am tempted to use the following that builds ok, but I have some doubts. Do you think that it is correct?
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 );
If I use a boost::static_pointer_cast
I have compiler error; since I am casting from a derived to a base should not be more correct a static_cast
?
Thanks for your help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该可以正常工作。
也许这些课程根本不相关?
也许这些类此时还不完整,因此编译器不知道这些类是相关的? (不过,这也会产生其他错误。)
This should work just fine.
Perhaps those classes are not related after all?
Perhaps those classes are incomplete at that point, so the compiler doesn't know that the classes are related? (This should produce other error as well, though.)
这应该按最初所述工作。派生类 * 会很高兴地转换为基类 * 来构造共享指针。正如所指出的,ideone 也会编译它。我建议您的 Boost 安装或编译器有问题。
或者,正如所指出的,您的代码的其余部分。
This should work as stated originally. A derived_class* will happily cast down to a base_class* with which to construct the shared_ptr. As pointed out, ideone will compile it too. I suggest there is something wrong with your Boost installation or compiler.
Or, as pointed out, the rest of your code.
需要类型强制才能执行此转换,这是通过成员模板实现的。这在旧的编译器上并没有得到很好的支持。因此,它在这些编译器上被禁用。你使用什么编译器?
Type coercion is needed to be able to do this cast, which is implemented via a member template. This is not too well supported on older Compilers. Therefore it is disabled on these compilers. What compiler are you using?