dynamic_cast

是什么:
动态类型转换,确保类型转换是有效转换
什么时候工作:
在程序运行时计算
怎么工作:
有运行时类型信息RTTI 存储了我们所以类型运行时的类型信息 所以能够判断类型转换是否合理
写法:
dynamic_cast<要转换的类型>(变量名);
代码示例:

class Entity
{
public:
	virtual ~Entity()
	{}
	
};
class Player :public Entity
{
	
};
class Enmy :public Entity
{};

int main()
{
	Player* player = new Player();
	Entity* entitymy = new Enmy();
	Player* p = dynamic_cast<Player*>(entitymy);
	if (p)
	{
		std::cout << "能转换";
	}
	else
		std::cout << "不能转换";

}
posted @ 2024-07-15 22:06  Wzline  阅读(2)  评论(0编辑  收藏  举报