C++中显式类型转换和隐式类型转换
一、显式类型转换
对于const变量
想要修改它的值应该怎么办?
const int age = 40;
int newAge = age;
newAge =18;
显然上述办法是不成立的,newAge变量有自己的存储地址,因此age始终没有变化。那通过指针这样可不可以?
const int age = 40;
const int *ageAddress = &age; //常变量只能用常指针
*ageAddress = 18;
那这,const的指针和const的变量一样还是没有办法修改啊!
那么还有什么别的办法吗?当然是有~~~使用类型转换。将const变量转换为非const变量。
C++提供了四个转换运算符:
const_cast <new_type> (expression)
static_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
dynamic_cast <new_type> (expression)
1、const_cast
用于将const变量转为非const
int main()
{
int age = 40;
const int agep = age;
cout << "const of age:" << agep << endl;
int &nConstAge = const_cast<int&>(agep);
// 修改nConstAge的值看看是否能成功修改age的值
nConstAge = 18;
cout << "new const of age:" << agep << endl;
system("pause");
return 0;
}
2、static_cast
用于将const变量转为非const
//用法
int constAge = static_cast<int&>(age);
3、dynamic_cast
用于动态类型转换。只能用于含有虚函数的类,用于类层次间的向上和向下转化。只能转指针或引用。向下转化是,如果是非法的对于指针返回NULL,对于引用跑一场。要深入了解内部转换的原理。
- 向上转换:指的是子类向基类的转换
- 向下转换:指的是基类想子类的转换
她通过判断在执行到该语句的时候变量的运行时类型和要转换的类型是否相同来判断是否能够向下转换。
4、reinterpret_cast
几乎什么都可以转,比如将int转指针,可能会出问题,尽量少用;
二、隐式类型转换
1. 算术转换
如果是不同类型的变量,计算±*/的时候,会出现类型转换,最后会转换成只有一种类型的式子进行运算。
在进行运算时,以表达式中最长类型为主,将其他类型位据均转换成该类型,如:
- 若运算数中有double型或float型,则其他类型数据均转换成double类型进行运算。
- 若运算数中最长的类型为long型.则其他类型数均转换成long型数。
- 若运算数中最长类型为int型,则char型也转换成int型进行运算。算术转换是在运算过程中自动完成的。
大致就是如下所示,算式中的变量会转换为长度更长的更高的类型。此种情况的的还有bool类型的变量,除0
之外,其他变量都会被bool类型转换为true
。
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int a = 2;
double b = 3.1415;
char c = 'a';
cout << typeid(a*b-c).name() << endl;
bool flag = 0.01;
cout << flag << endl;
system("pause");
return 0;
}
2. 赋值转换
进行赋值操作时,赋值运算符右边的数据类型必须转换成赋值号左边的类型,若右边的数据类型的长度大于左边,则要进行截断或舍入操作。
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int a = 2;
double b = 3.1415;
char c = 'a';
/*
1. a-->double
2. c-->int 原式就变成了 double-int
3. int-->double
原始式子就是变成了 int = double
最后等号部分,double-->int
*/
int result = a*b-a*c;
system("pause");
return 0;
}
3. 输出转换
输出转换就是在程序中用printf()函数以指定格式输出,当要输出的数据类型与输出格式不符合时,会转化为以输出格式的输出形式。
char a = 'a';
printf("输出a的ASCII值:%d", a); //输出“输出a的ASCII值:97”