C++语言级别提供的四种类型转换方式

1.const_cast:去掉常量属性的类型转换
int main() {
	//const_cast:去掉常量属性的类型转换
	const int a = 10;
	int* p1 = (int*)&a;
	int* p2 = const_cast<int*>(&a);//相当于一个模板,尖括号中是想转换成的类型
	//两种方式产生的汇编指令完全相同
	//但是传入的类型或指针类型与原类型不相符,const_cast会报错。而强转则没有限制
	//int b = const_cast<int>a;报错:const_cast 中的类型必须是指针、引用或指向对象类型成员的指针

	return 0;
}
2.static_cast:提供编译器认为安全的类型转换

“静态”static和“动态”dynamic相对,一般情况使用的最多的是static_cast

int main() {

	int a = 10;
	char b = static_cast<char>(a); //尖括号中是想转换成的类型
	cout << typeid(b).name() << endl << b << endl;

	/*int* p1 = nullptr;
	short* p2 = static_cast<short*>(p1);报错:不支持这种无意义的类型转换,编译器只转换认为有联系的类型*/

	return 0;
}

static_cast可以支持基类和派生类间的类型转换

3.reinterpret_cast:类似C风格的强制类型转换
int main{
	int* p1 = nullptr;
	double* p2 = reinterpret_cast<double*>(p1);
	//支持转换,尽管不安全
	return 0;
}
4.dynamic_cast:主要用于继承结构中,可以支持RTTI类型识别的上下转换
class Base {
public:
	virtual void func() = 0;
};
class Derive1 :public Base {
public:
	void func() {
		cout << "call Derive1::func()" << endl;
	}
};
class Derive2 :public Base {
public:
	void func() {
		cout << "call Derive2::func()" << endl;
	}
};
void showFunc(Base* p) {
	p->func();
}

给Derive2添加一个API接口D2func(),增加需求:当使用Derive2类型指针调用showFunc(Base* p)时,调用它的D2func()而不是func()

class Derive2 :public Base {
public:
	void func() {
		cout << "call Derive2::func()" << endl;
	}
	void D2func() {
		cout << "call Derive2::D2func()" << endl;
	}
};
void showFunc(Base* p) {
	//dynamic_cast会检查p是否指向一个Derive2类型对象,如果是,返回该Derive2对象地址,如果不是,返回nullptr
	//static_cast是静态转换,查看的是编译时期的类型。dynamic_cast会去RTTI中查看运行时期的类型
	Derive2* pd2 = dynamic_cast<Derive2*>(p);
	if (pd2 == nullptr) {
		pd2->func();
	}
	else {
		pd2->D2func();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值