为什么C ++允许将指向基础对象的指针转换为派生类的指针 [英] Why C++ allow converting pointer to base object into pointer of derived class
问题描述
可能重复:
使用C ++中的Static_cast进行下转
我很困惑,我们什么时候需要将指针转换为基础对象转换为派生类的指针?
任何人都可以帮我给我一些例子。
I'm very confused by when do we need to convert pointer to base object into pointer of derived class? Can anyone do me a favor to give me some example?
推荐答案
想象你有一个基类 Animal
和两个派生类 Cat
和 Dog
。
Imagine you have a base class Animal
and two derived classes, Cat
and Dog
.
// Assume methods are public.
class Animal { virtual void Attack(); }
class Dog : public Animal { void Meow(); }
class Cat : public Animal { void Bark(); }
我们可以使用 base class 指针引用我们的派生对象。这有助于我们现在可以将它们包含为相同类型。
We can use base class pointers to reference our derived objects. This helps as we can now contain them as the same type.
Animal* myCat = new Cat;
Animal* myDog = newDog;
std::vector<Animal*> myAnimals;
myAnimals.push_back(myCat);
myAnimals.push_back(myDog);
这很有用,因为我们可以调用所有各种动物的基础成员函数,类类型。
This is useful, as we can call base member functions all all kinds of animals, regardless of their derived class types.
// Call Attack() on every cat and dog.
for_each(myAnimals.begin(), myAnimals.end(), [](auto& e) { e->Attack(); });
您可以使用动态投射测试其中一个基本指针被转换为派生类指针。
You can use dynamic casting to test if one of the base pointers can be converted into a derived class pointer.
Cat* realCat = dynamic_cast<Cat*> myAnimals[0]; // Success. Pointer is valid.
Cat* fakeCat = dynamic_cast<Cat*> myAnimals[1]; // Failure, it's not a cat. NULL.
现在可以调用您的成员方法,例如 Meow code>从派生类指针。这是不可能的,因为
Animal
没有这些方法。
You can now call your member methods, such as Meow()
from the derived class pointers. This was not possible before, as Animal
does not have these methods.
realCat->Meow(); // Valid.
myCat->Meow(); // Animal*, there is not Meow() method.
这篇关于为什么C ++允许将指向基础对象的指针转换为派生类的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!