C++中的类型转换(static_cast,reinterpret_cast,const_cast,dynamic_cast,explicit关键字)

C++中的类型转换

1、C语言中的类型转换

分为隐式类型转换和显示类型转换

1.2、C语言中的类型转换存在缺陷

1、隐式类型转换可能出现未知错误
2、显示类型转换导致代码不够清晰
3、转换的可视性差,难以追踪错误

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main()
{
	int i = 1;
	double d = 1;//隐式类型转换
	printf("%d %.2f\n", i, d);

	int* p = &i;
	int address = (int)p;//显示类型转换
	printf("%x %d\n", p, address);
	system("pause");
	return 0;
}

2、static_cast

static_cast用于非多态类型的转换,编译器执行的任何类型转换都可用static_cast,但它不能用于两个不相关类型进行转换

#include <iostream>

using namespace std;

int main()
{
	double d = 12.34;
	int a = static_cast<int>(d);
	cout << a << endl;
	system("pause");
	return 0;
}

3、reinterpret_cast

reinterpret_cast操作符通常为操作数的位模式提供较低层次的重新解释,用于将一种类型转换为另一种不同的类型

#include <iostream>

using namespace std;

typedef void (*FUNC)();

int doSomething(int i)
{
	cout << "doSomething()" << endl;
	return 0;
}

int main()
{
	FUNC f = reinterpret_cast<FUNC>(doSomething);
	f();
	system("pause");
	return 0;
}

4、const_cast

const_cast可以去掉变量的const属性

#include <iostream>

using namespace std;

int main()
{
	const int a = 2;
	int* p = const_cast<int*>(&a);
	*p = 3;
	cout << a << endl;
	system("pause");
	return 0;
}

5、dynamic_cast

dynamic_cast用于将一个父类对象的指针转换为子类对象的指针或引用(动态转换)
向上转型:子类对象指针->父类对象指针/引用(不需要转换,赋值兼容规则)
向下转型:父类对象指针->子类对象指针/引用(用dynamic_cast转型是安全的)

注:
1、dynamic_cast只能用于含有虚函数的类
2、dynamic_cast会先检查是否能转换成功,能成功转换则转换,否则返回0
3、强制类型转换会关闭或挂起正常的类型检查。

#include <iostream>

using namespace std;

class A
{
public:
	virtual void f()
	{

	}
};

class B : public A
{

};

void fun(A* pa)
{
	B* pb1 = static_cast<B*>(pa);
	B* pb2 = dynamic_cast<B*>(pa);

	cout << "pb1:" << pb1 << endl;
	cout << "pb2:" << pb2 << endl;
}

int main()
{
	A a;
	B b;
	fun(&a);
	fun(&b);
	system("pause");
	return 0;
}

6、explicit关键字

explicit关键字是阻止经过转换构造函数进行隐式转换的发生

#include <iostream>

using namespace std;

class A
{
public:
	explicit A(int a)
	{
		cout << "A(int a)" << endl;
	}

	A(const A& a)
	{
		cout << "A(const A& a)" << endl;
	}
private:
	int m_a;
};

int main()
{
	A a1(1);
	A a2 = 1;
	system("pause");
	return 0;
}

7、RTTI

RTTI(Run-time Type identification)运行时类型识别
C++通过typeid运算符和dynamic_cast运算符来支持RTTI

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值