对于父类Entity,有两个子类:Player,Enemy。如果定义一个 Entity* 类型变量,如下
Entity* actuallyEnemy = new Enemy();
即用Enemy类的构造函数为变量赋值,默认会发生子类向父类的类型转换,不会有问题
如果此时将该变量赋给Player类型的指针,就会出问题
Player* player = actuallyEnemy;
为了避免这种错误的类型转换,需要用到dynamic_cast
Player* p0 = dynamic_cast<Player*>(actuallyEnemy);
此时,因为actuallyEnemy是Enemy*类型,所以类型转换错误,系统设置p0为null。通过判断p0,可以确认类型转换的对错
全部代码如下:
#include <iostream>
#include <string>
class Entity {
public:
virtual void PrintName() {}
};
class Player : public Entity {
};
class Enemy : public Entity {
};
int main() {
Player* player = new Player();
Entity* actuallyEnemy = new Enemy();
Entity* actuallyPlayer = player;
Player* p0 = dynamic_cast<Player*>(actuallyEnemy);
Player* p1 = dynamic_cast<Player*>(actuallyPlayer);
if (p0) {
std::cout << "p0 is a turely player!" << std::endl;
}
else {
std::cout << "p0 is not a player!" << std::endl;
}
if (p1) {
std::cout << "p1 is a turely player!" << std::endl;
}
else {
std::cout << "p1 is not a player!" << std::endl;
}
std::cin.get();
}