#include <iostream>
#include <string>
// what dynamic cast does is specifically it's used for cast along the inheritance hierarchy.
// base type to derived type or derived type to base type.
// return null if it's an unvalid cast.
// costs a bit time to check the type at runtime, added overhead to the program.
class Entity
{
public:
virtual void PrintName(){}
};
class Player : public Entity
{
};
class Enemy : public Entity
{
};
int main(void)
{
Player* player = new Player();
Entity* actuallyEnemy = new Enemy();
Entity* actuallyPlayer = player;//implicit cast.
Player* p0 = dynamic_cast<Player*>(actuallyEnemy);
if (p0)
{
}
Player* p1 = dynamic_cast<Player*>(actuallyPlayer);
std::cin.get();
}
【Cherno的C++视频】Dynamic casting in C++
于 2022-08-15 19:46:57 首次发布