c++:四种类型转换

c++中共分为四种类型转换

static_cast<T>(expr) 、reinterpret_cast<T>(expr) 、dynamic_cast<T>(expr) 、const_cast<T>(expr) 。

下面我们通过代码来了解每个类型转换的作用。

1、static_cast<T>(expr) 

注意:c和c++的功能实现的不同

在c++中的作用:

(1)用于普通类型间的转换

(2)用于有继承关系类之间的转换

(3)用于有继承关系类指针之间的转换

#include<iostream>
using namespace std;

class A                   //定义一个空类
{
};

class B : public A        //B继承于A
{ 
};

int main()
{
	int a=1;
	double b;
	a=(int)b;                       //c中,强制转换
	a=static_cast<int>(b);          //c++中,用于普通类型间的转换

	char c;
	int *pa;
	char *pc;
	pa = (int *)pc;                   //c中,强制转换
	//pa = static_cast<int *>(pc);    //错误,不能用于基本类型指针间的转换
	
	A aa;
	B bb;
	aa = static_cast<A>(bb);       //c++中,用于有继承关系类之间的转换
	//bb = static_cast<B>(aa);     //错误,基类对象不能给派生类
	
	A *pa1;
	B *pb1;
	//c++ 用于有继承关系类指针之间的转换
	pa1 = static_cast<A *>(&bb);       //基类指针指向派生类对象
	
	return 0;
}

2、reinterpret_cast<T>(expr)

在c++中的作用:

(1)用于基本指针类型之间的转换

(2)用于整数和指针之间的转换

#include<iostream>
using namespace std;

int main()
{
	int a=1;
	char b = 'a';
	int *pa = &a;
	char *pb = &b;
	
	pa = reinterpret_cast<int *>(pb);       //用于基本指针类型之间的转换

	pb = reinterpret_cast<char *>(0x100);   //用于整数和指针之间的转换
	
	return 0;
}

3、dynamic_cast<T>(expr) 

在c++中的作用:

(1)用于多态性的父子类型对象的指针或引用之间

#include<iostream>
using namespace std;

class A
{
private:
	int m_a;
public:
	virtual void show()
	{
		
	}
};

class B : public A
{
private:
	int m_b;
public:
	virtual void show()
	{
		
	}
};

int main()
{
	A a;
	B b;
	A *pa = &a;
	B *pb = &b;
	
	pa = &b;
	pa = dynamic_cast<A *>(&b);
	
	pb = static_cast<B *>(&a);
	//pb = dynamic_cast<B *>(&a);      //错误,加了dynamic_cast 有警告
                                       //把这句话中的dynamic_cast改为static_cast就正确了
	
	return 0;
}

4、const_cast<T>(expr)

在c++中的作用:

(1)修改类型的const或volatile属性

#include<iostream>
using namespace std;

int main()
{
	const int a=1;
	int *pa = const_cast<int *>(&a);        //去掉变量const属性
	
	const int &b = 1;
	int &c = const_cast<int &>(b);          //打印出来的结果为2
	c = 2;
	cout<< b <<endl;
	
	const int d = 1;                        //d是常量  不改变数值  
	int &e = const_cast<int &>(d);
	e = 2;
	cout<< d <<endl;                        //打印出来的结果为1
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xutong98/article/details/81384863