【Cherno的C++视频】Casting in C++

这篇博客探讨了C++中的类型转换,包括static_cast、dynamic_cast、const_cast和reinterpret_cast的用法。通过一个示例展示了如何在类继承体系中进行安全的类型转换,特别强调了dynamic_cast在运行时检查类型转换的重要性。
摘要由CSDN通过智能技术生成
#include <iostream>

// type casting.
// static_cast: will do compile time checking.
// dynamic_cast: will do run time checking, it'a great way to see if it's actually worked.
// const_cast: to add or remove const.
// reinterpret_cast: basically like what you did in TypePunning.

class Base
{
public:
	Base() {}
	virtual ~Base() {}
};

class Derived : public Base
{
public:
	Derived() { }
	~Derived() { }
};

class AnotherClass : public Base
{
public:
	AnotherClass() { }
	~AnotherClass() { }
};
int main(void)
{
	double value = 5.25;
	double a = (int)value + 5.3;				//c style cast.
	double b = static_cast<int>(value) + 5.3;	//cpp style cast, make your code more solid.

	Derived* derived = new Derived();
	Base* base = derived;
	AnotherClass* anotherClass = dynamic_cast<AnotherClass*>(base);
	if (!anotherClass)
	{
		std::cout << "dynamic_cast<AnotherClass*>(base) is failed!\n";
	}
	Derived* de = dynamic_cast<Derived*>(base);
	if (de)
	{
		std::cout << "dynamic_cast<Derived*>(base) is successful!\n";
	}

	std::cin.get();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值