xxx_cast类型转换

类型转换

  • 隐式类型转换
  • 显式类型转换

1.static类型转换 

2.const类型转换 

#include<iostream>
#include<vector>
using namespace std;

int main(){
	int* n = NULL;
	void* p = n;//隐式转换 
	//C语言类型转换方式 
	n = (int*)p;//显式转换 
	
	char c = 'a';
	cout << c << endl;
	cout << (int)c << endl;//打印ASCII码 
	
	const char* s = "abcdef";
	cout << s << endl;
	cout << (void*)s << endl;//地址 

	// 1.static_cast
	n = static_cast<int*>(p);//显式转换
	cout << static_cast<int>(c) << endl;
	cout << static_cast<const void*>(s) << endl;
	
	// 2.const_cast 把const转成非const
	const int m = 10; 
	//m = 100; 直接报错
	const_cast<int&>(m) = 100;//要引用&
	cout << m << endl; //但输出还是10
	int*q = const_cast<int*>(&m);//把m的地址取出来
	cout << *q << endl; 
	
	const vector<int> vec = {1,2,3,4};
	//vec[1] = 10; 会报错
	
	const_cast<vector<int>&>(vec)[1] = 10;
	
	for(auto n:vec) cout << n << " ";
	cout << endl;	
}

或:在需要修改的成员变量声明前加上关键字mutable

mutable int getter;

 3.dynamic类型转换 

#include<iostream>
#include<vector>
using namespace std;

//多态: 
class Base{
public:
	virtual void Test(){
		cout << "Base:" << __func__ << endl; 
	}
};
class Derive:public Base{
public: 
	virtual void Test(){
		cout << "Derive:" << __func__ << endl; 
	}
	void Func(){
		cout << "Derive:" << __func__ << endl;
	}
};

int main(){
	//3.dynamic_cast 多态父对象指针转成子对象指针
	Base * k = new Derive;
	k->Test(); 
	Derive* kk = dynamic_cast<Derive*>(k);//因为父类中没有Func() 
	kk->Func(); 
}

  4.reinterpret类型转换 

No.转换转换对象作用转换时机
1static_cast基本类型、指针、引用实现传统的小括号转化功能在编译期间实现转换
2const_castconst类型的对象、指针、引用移除变量const限定在编译期间实现转换
3dynamic_cast类的指针、类的引用或者void *多态父类指针/引用转化成子类指针/引用在运行期间实现转换,并可以返回转换成功与否的标志/抛出异常
4reinterpret_cast指针、引用、算术类型万能强制类型转换在编译期间实现转换

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值