C++专属类型转换static_cast、reinterpret_cast、dynamic_cast、const_cast

C++ 风格的类型转换

C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统都是
TYPE b = (TYPE)a;
C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。

  1. static_cast 静态类型转化。如int转换为char
  2. reinterpret_cast 重新解释类型
  3. dynamic_cast 动态类型转换。如子类和父类之间的多态类型转换
  4. const_cast 去const属性
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

//C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统都是
	//TYPE b = (TYPE)a;
//C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。
	//1 static_cast			静态类型转化。如int转换为char
	//2 reinterpret_cast	重新解释类型
	//3 dynamic_cast		动态类型转换。如子类和父类之间的多态类型转换
	//4 const_cast			去const属性
//4种类型转换的格式:
	//以 1 为例:TYPE B = static_cast<TYPE>(a);
class Animal
{
public:
	virtual void cry() = 0;
protected:
private:
};

class Dog :public Animal
{
public:
	virtual void cry()
	{
		cout << "woof woof woof!" << endl;
	}
	void watchHome()
	{
		cout << "Watch home!" << endl;
	}
};

class Cat :public Animal
{
public:
	virtual void cry()
	{
		cout << "mew mew mew!" << endl;
	}
	void watchHome()
	{
		cout << "Catch rats!" << endl;
	}
};

void playObj(Animal* base)
{
	//base->cry();//实现多态
	//dynamic_cast运行时类型识别
	Dog* pDog = dynamic_cast<Dog*>(base);//父类对象====>子类对象
										 //可实现向下转型:把老子转成小子
	if (pDog != NULL)
	{
		pDog->cry();
		pDog->watchHome();
	}

	Cat* pCat = dynamic_cast<Cat*>(base);
	if (pCat != NULL)
	{
		pCat->cry();
		pCat->watchHome();
	}
}

void printBuf(const char* p)
{
	char* p1 = NULL;
	//程序员要清楚的知道 变量转换前是什么类型,转换之后是什么类型
	//const char* ====> char* :去掉只读属性
	p1 = const_cast<char*>(p);

	p1[0] = 'X';
	p1[1] = 'V';
	cout << endl << p << endl;
}

int main()
{
	double dpi = 3.1415926;

	int num1 = (int)dpi;//C类型转换
	int num2 = static_cast<int>(dpi);//静态类型转换 编译时C++编译器会做类型检查
	int num3 = dpi;//C语言中可以隐式类型转换的地方,均可使用`static_cast<>()`进行类型转换

	//char* ===> int*
	char* p1 = new char[100];
	strcpy(p1, "helloWorld!");
	int* p2 = NULL;
	//p2 = static_cast<int*>(p1);//使用static_cast,编译器编译时会做类型检查,有错报错
	
	p2 = reinterpret_cast<int*>(p1);//用reinterpret_cast<>()进行重新解释

	cout << "p1: " << p1 << endl;//输出本身
	cout << "p2: " << p2 << endl << endl;//输出首地址的十进制表示

	//总结:通过static_cast<>()和reinterpret_cast<>()把C语言的强制类型转化都覆盖了
	//static_cast<>()和reinterpret_cast<>()各司其职,不能混用
	delete[] p1;

	Dog d1;//dynamic_cast<>();
	Cat c1;

	Animal* pBase = NULL;

	pBase = &d1;
	pBase = static_cast<Animal*>(&d1);//C++编译器在编译的时候进行类型检查,故可通过

	pBase = reinterpret_cast<Animal*>(&d1);//重新解释类型

	playObj(&d1);
	playObj(&c1);

	char buf[] = "aaaaaaaaaaaaaaaaa";
	printBuf(buf);

	return 0;
}

输出

p1: helloWorld!
p2: 00115378

woof woof woof!
Watch home!
mew mew mew!
Catch rats!

XVaaaaaaaaaaaaaaa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

banjitino

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值