类型转换分为两种:
1. 显示类型转换
2. 隐式类型转换(非常危险)
隐式类型转换常见于各种函数的传参, 以及 不同类型变量间的运算等等。
在这里, 我们来着重的 了解显示类型转换。
在 c 风格的类型转换中, 表现形式没有那么清晰名了,容易被看漏,多以一旦转换过程出现问题,追踪起来也更加困难。
eg: (int) ant;
在c++中,我们有新的方式可以用来使用,
cast<type>(expression)
cast ——>以何种方式进行转换 type ——> 要转换成的数据类型 expression ——> 要转换的变量
eg: static_cast<double>(变量名)
c++有以下三种 强制类型转换命令:
1. static_cast
除了底层的const, 都能改变
#include <vector>
using namespace std;
int n, m;
int main()
{
int a = 999;
int cha1 = static_cast<char>(a)/9; //除了底层const都能转换(底层const是指对象为常量)
cout << cha1 << endl;
}
2. const_cast
只能改变底层的 const
#include <vector>
using namespace std;
int n, m;
int main()
{
const char *pc = "plus"; //定义了一个底层const
char *p = const_cast<char*>(pc);//把底层const强制转换为一般指针
cout << *p << endl;
}
3. reinterpret_cast
会消除编译器的警告,促使编译器将某种类型 当成 解释的的类型编译, 但是这种做法非常的危险!!!不推荐使用
#include <vector>
using namespace std;
int n, m;
int main()
{
int temp = 999;
int* pd = &temp;
char* pp = reinterpret_cast<char*>(pd);
string str(pp);
}
编程中,不要将 无符号类型 与 有符号类型进行比较, 这是非常危险的!!!
类类型的隐式类型转换
用explicit 在类内部声明 只有一个参数的 构造函数。可以避免隐式类型转换的发生。
explicit List(size_type n, value_type val):List()
{
while(n--) push_back(val);
}
我们以List的构造函数为例, 传入 n 个 val, 这个时候我们就要加上 explict 来防止隐式类型转换的发生.
比如: n = -1;
unsigned int a = (unsigned)-1;
printf("%u\n",a); //输出结果是 4294967295
可不可怕?? 吓不下人??