有没有办法将抽象 object 转换为它的 child?

Is there a way to cast an abstract object to its child?

让我们想象这样一种情况,我有一个名为 'Base' 的抽象 class 和一个名为 foo() 的虚拟纯方法,以及两个都实现的 children(Inherited1 和 Inherited2)这种方法以他们自己的方式。现在假设其中一个 children (Inherited1) 需要另一个名为 bar() 的方法,该方法在 Inherited2.

中实现毫无意义

我主要有

Base * randomObject = new Inherited1();

我无法使用

访问此方法
random->bar();

我该怎么办。就像我说的,在 inherited2 中实现它是没有意义的,所以我不能简单地在 Base 中放置另一个虚拟方法,或者我应该吗?

如果你有一个变量

Base* randomObject = new Inherited1();

你可以把它扔到底部 class

Inherited1* foo = static_cast<Inherited1*>(randomObject);
foo->bar();

但是你必须确保指针确实是 that 派生的 class 否则 static_cast 是不安全的。有很多方法可以做到这一点,例如将 enum 存储在派生的 class 中,您可以通过 virtual getter 进行检查,或者检查结果是否dynamic_castnullptr,但速度较慢。