C++类型转换

类型转换

     类型转换(cast)是将一种数据类型转换成另一种数据类型。

静态转换 static_cast<目标类型>(转换数据)

1、可以转换基本数据类型

//静态类型转换static_cast<类型>(原始数据)
void static_change() {
	int a = 10;
	double b = static_cast<double>(a);

	char c = 'a';
	int d = static_cast<int>(c);
	cout << d << endl;
	//cout << b << endl;
}

2、基类和派生类型转换

如果没有继承关系的自定义类型不可以进行转换

//父子类型转换
class Base
{
public:
	virtual void dowork() {};

private:

	int m_age;
	string name;
};

class Person :public Base
{
public:
	virtual void dowork() {};


private:
	int salary;

};


void test1()
{
	Base A;
	Person B;

	cout << typeid(B).name() << endl;

	//子转父可以
	A = static_cast<Base>(B);

	//父转子,不可以,不安去
	//B = static_cast<Person>(A);
	cout << "转换后:"<<typeid(static_cast<Base>(B)).name() << endl;


};

 

 

动态转换 dynamic_cast<目标类型>(转换数据)

  1. 不可以转换基础数据类型
  2. 父子之间可以进行转换
    1. 父转子,不可以,不安去
    2. 子转父,可以
    3. 如果发生多态,都可以进行

 

void test04()
{
	Base2* base = NULL;
	Child2* child = NULL;

	//child转Base2 *  安全
	Base2* base2 = dynamic_cast<Base2*>(child);


	//base 转Child2 * 不安全
	//Child2 * child2 = dynamic_cast<Child2*>(base);

	//dynamic_cast 如果发生了多态,那么可以让基类转为派生类 ,向下转换
	Base2* base3 = new Child2;
	Child2* child3 = dynamic_cast<Child2*>(base3);

}

 

 

常量转换 const_cast<目标类型>(转换数据)

// 常量转换(const_cast)
void test05()
{
	const int * p = NULL;
	//取出const
	int * newp = const_cast<int *>(p);

	int * p2 = NULL;
	const int * newP2 = const_cast<const int *>(p2);


	//不能对非指针 或 非引用的 变量进行转换
	//const int a = 10;
	//int b = const_cast<int>(a);

	//引用
	int num = 10;
	int &numRef = num;

	const int &numRef2 = static_cast<const int &>(numRef);
}

 

重新解释转换 reinterpret_cast<目标类型>(转换数据)

//重新解释转换(reinterpret_cast)
void test06()
{
	int a = 10;
	int * p = reinterpret_cast<int *>(a);


	Base * base = NULL;
	Other * other = reinterpret_cast<Other*>(base);

	//最不安全 ,不推荐

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值