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