C++ 类型转换(自学笔记 可能有误)

类型转换名称和语法

C风格的类型转换      Type b = (Type)a;

C++类型转换提供了4中类型转换操作符来对应不同场合的应用

(1)static_cast                静态类型转换

(2)reinterpreter_cast     重新解释类型

(3)dynamic_cast           命名上理解是动态类型转换。如子类和父类之间的多态类型转换

(4)const_cast               字面上理解就是去除const属性

 

类型转换一般性介绍

static_cast 

(1)一般C语言能隐式转换的它都可以转换成功,编译时C++编译器会做类型检查,转换不过去的会进行报错,基本类型能转换,但是不能转换指针类型

reinterpreter_cast 

(1)若不同类型之间,进行强制类型转换,用它对类型进行重新解释

 

static_cast 和reinterpreter_cast  的总结

static_cast 和reinterpreter_cast 把C语言的强制类型转换都包括了

#include <iostream>
using namespace std;


int main()
{

	double pi = 3.1415926;

	int num = (int)pi;

	int num2 = static_cast<int>(pi);  //静态类型转换

	char * p1 = (char *)"hello ";
	int * p2 = NULL;
	//p2 = p1;     static_cast  无法转换指针类型

	p2 = reinterpret_cast<int*>(p1);
	cout << p1 << endl;    //这里输出的是指针指向的内容 相当于 %s
	cout << p2 << endl;    //这里只是输出指针指向的地址 相当于 %d
	return 0;
}

dynamic_cast

(1) 用在多态中,父类到子类的向下转型

(2) 在运行时进行类型识别

#include <iostream>
using namespace std;


class father
{
public:
	virtual void SelfIntroduction() = 0;
};

class son1 :public father
{
public:
	virtual void SelfIntroduction()
	{
		cout << "我是son1" << endl;
	}
	void Print()
	{
		cout << "我是长子" << endl;
	}
};

class son2 :public father
{
public:
	virtual void SelfIntroduction()
	{
		cout << "我是son2" << endl;
	}
	void Print()
	{
		cout << "我是次子" << endl;
	}
};


void playObj(father * obj)
{
	obj->SelfIntroduction();
	son1 * S1 = dynamic_cast<son1*>(obj);  //这里可以识别类型 强制转换不能识别类型
	if (S1 != NULL)
	{
		S1->Print();
	}


	son2 * S2 = dynamic_cast<son2*>(obj);  
	if (S2 != NULL)
	{
		S2->Print();
	}
}
int main()
{
	son1 s1;
	son2 s2;
	playObj(&s1);
	playObj(&s2);

	return 0;
}

 

const_cast 

主要的应用场景就是去除变量的只读属性

//const char *p的const修饰 让p指向的内存空间 变成只读属性
void printfbuff(const char *p)
{
	//p[0] = 'Z'; 直接修改会报错
	char * p1 = NULL;
	p1 = const_cast<char *>(p);  //将const char*  转换为 char *
	p1[0] = 'Z';
	cout << p << endl;
}

int main()
{
	char buff[] = "12344556";
	printfbuff(buff);

	//要保证p指向的内存空间确实是可以修改的,如果不能修改会带来灾难性后果

	return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值