Why can#39;t I dynamic_cast quot;sidewaysquot; during multiple inheritence?(为什么我不能动态投射“横向?在多重继承期间?)
问题描述
以下代码抛出 std::bad_cast
The following code throws std::bad_cast
struct Foo {
void foo () {}
};
struct Bar {
Bar () {
dynamic_cast <Foo &> (*this) .foo ();
}
virtual ~ Bar () {}
};
struct Baz : public Foo, public Bar {
};
int main ()
{
Baz b;
}
我记得曾经读过 dynamic_cast 如何权衡实现性能,因为它遍历完整的继承格"以便正确评估.这里编译器要做的就是先上投再下投.
I remember once reading how dynamic_cast has implementation performance trade-offs because "it traverses the full inheritence lattice" in order to evaluate correctly. What the compiler needs to do here is first cast up and then down again.
是否有可能使上述工作或我需要添加虚拟Foo* Bar::as_foo()=0;?
Is it possible to make the above work or do I need to add
virtual Foo* Bar::as_foo()=0;
?
推荐答案
Foo 中没有虚函数,因此 dynamic_cast 完全不得不失败.需要有一个虚函数.在施工期间这样做也是一个坏主意,因为您会遇到施工订单问题.
There are no virtual functions in Foo, so dynamic_cast is perfectly obliged to fail. There needs to be a virtual function. It's also a bad idea to do so during construction, as you're going to run into construction order issues.
这篇关于为什么我不能动态投射“横向"?在多重继承期间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能动态投射“横向"?在多重继承期间?
基础教程推荐
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
