[英]Pointers pointing in Inherited classes
Suppose we have a BaseClass Character and three SubClasses Good, Bad, Zombie. 假设我们有一个BaseClass角色和三个子类Good,Bad,Zombie。 Also assume we have two pointers
还假设我们有两个指针
Character* ptr1,ptr2;
that point in class Good,Bad or Zombie. 在Good,Bad或Zombie类中的这一点。 I want to create a part of code like this:
我想创建一部分这样的代码:
if ((ptr1 "shows" Good)&&(ptr2 "shows" Bad)) {...} else if ((ptr1 "shows" Good)&&(ptr2 "shows" Zombie)) {...} else if ...
and so on. 等等。 How can I write such a statement?
我该如何写这样的声明? I have a hard time understanding virtual functions, polymorphism and inheritance but feel free to explain in terms of those too.
我很难理解虚函数,多态性和继承,但也可以自由地解释这些功能。
Thank you, in advance. 先感谢您。
You could declare a virtual public method in Character that returns an enum class representing the type of character, for example 您可以在Character中声明一个虚拟的公共方法,该方法返回一个表示字符类型的枚举类,例如
virtual CharacterType GetCharacterType();
....
if((ptr1->GetCharacterType() == CharacterType::Good) && ptr2->GetCharacterType() == CharacterType::Bad)) {...}
or a virtual method that confirms the type of character. 或确认字符类型的虚拟方法。
virtual bool Is(CharacterType characterType);
....
if((ptr1->Is(CharacterType::Good) && ptr2->Is(CharacterType::Bad)) {...}
You could use dynamic_cast
in the following manner: 您可以通过以下方式使用
dynamic_cast
:
if (dynamic_cast<Good*>(ptr1) && dynamic_cast<Bad*>(ptr2)) {
...
} else if (dynamic_cast<Good*>(ptr1) && dynamic_cast<Zombie*>(ptr2)) {
...
} else if ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.