c++中的类型转换

#include<iostream>//33
#include<cstdlib>
using namespace std;
/*c 风格的强制类型转化很简单,double a = 3.1415; int b = <int> a;
c++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。
static_cast		静态类型转换:int 转换成 char
reinterpret_cast重新解释类型
dynamic_cast	用于子类父类之间的多态类型转换
const_cast		去掉const(只读)属性
4中类型转换的格式:TYPE B = static_cast<TYPE>(a);*/

//const char *p;的const修饰的是p指向的内存空间,即值,变成只读属性

class Animal
{
public:
	virtual void cry() = 0;
};

class Dog:public Animal
{
public:
	virtual void cry()
	{
		cout << "旺旺" << endl;
	}
	void doHome()
	{
		cout << "看门" << endl;
	}
};

class Cat :public Animal
{
public:
	virtual void cry()
	{
		cout << "喵喵" << endl;
	}
	void doThing()
	{
		cout << "捉老鼠" << endl;
	}
};

void playObjAnimal(Animal *base)
{
	base->cry();//有继承 虚函数重写 父类指针指向子类对象==》多态
	Dog *pDog = dynamic_cast<Dog *>(base);//父类对象==》子类对象,向下转型
	if (pDog != NULL)
	{
		pDog->doHome();//让狗做自己特有的工作
	}

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

void printBuf(const char *p)
{
	char *p1 = NULL;
	p1 = const_cast<char *>(p);
	//p1[0] = 'R';//通过p1去修改了内存空间,p和p1都指向这块内存空间
	//cout << p1 << 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 *p1 = "RITA";
	int *p2 = NULL;
	//p2 = static_cast<int *>(p1);//会报错:类型转换无效
	p2 = reinterpret_cast<int *>(p1);//不会报错

	cout << p1 << endl;//p1所指向内存空间的内容,即字符串
	cout << p2 << endl;//字符串的起始地址
	//总结:通过 reinterpret_cast<>() 和 static_cast<>()把C语言的强制类型转换 都覆盖了
	//===============================================================================
	Cat c1;
	playObjAnimal(&d1);
	playObjAnimal(&c1);
	//===============================================================================
	char buf[] = "Rita love coding";
	char *p = "Rita love coding";
	printBuf(p);

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值