在C++语言中新增了四个关键字static_cast、const_cast、reinterpret_cast和dynamic_cast。这四个关键字都是用于强制类型转换的。我们逐一来介绍这四个关键字。
1) static_cast
#include<iostream> using namespace std; int main() { int num1 = 10; int num2 = 20; // double result = static_cast<double>(num2) / static_cast<double>(num1); double result = (double)num2 / (double)num1; cout<<result<<" "<<endl; cout << num1 << endl; return 0; }
2) const_cast
在C语言中,const限定符通常被用来限定变量,用于表示该变量的值不能被修改。而const_cast则正是用于强制去掉这种不能被修改的常数特性,但需要特别注意的是const_cast不是用于去除变量的常量性,而是去除指向常数对象的指针或引用的常量性,其去除常量性的对象必须为指针或引用。
#include<iostream> using namespace std; int main() { const int a = 10; const int * p = &a; int *q; q = const_cast<int *>(p); *q = 20; //fine cout <<a<<" "<<*p<<" "<<*q<<endl; cout <<&a<<" "<<p<<" "<<q<<endl; return 0; }
在本例中,我们将变量a声明为常量变量,同时声明了一个const指针指向该变量(此时如果声明一个普通指针指向该常量变量的话是不允许的,Visual Studio 2010编译器会报错),之后我们定义了一个普通的指针*q。将p指针通过const_cast去掉其常量性,并赋给q指针。之后我再修改q指针所指地址的值时,这是不会有问题的。
最后将结果打印出来,运行结果如下:
10 20 20
002CFAF4 002CFAF4 002CFAF4
查看运行结果,问题来了,指针p和指针q都是指向a变量的,指向地址相同,而且经过调试发现002CFAF4地址内的值确实由10被修改成了20,这是怎么一回事呢?为什么a的值打印出来还是10呢?
其实这是一件好事,我们要庆幸a变量最终的值没有变成20!变量a一开始就被声明为一个常量变量,不管后面的程序怎么处理,它就是一个常量,就是不会变化的。试想一下如果这个变量a最终变成了20会有什么后果呢?对于这些简短的程序而言,如果最后a变成了20,我们会一眼看出是q指针修改了,但是一旦一个项目工程非常庞大的时候,在程序某个地方出现了一个q这样的指针,它可以修改常量a,这是一件很可怕的事情的,可以说是一个程序的漏洞,毕竟将变量a声明为常量就是不希望修改它,如果后面能修改,这就太恐怖了。
接下来主要是const_cast的使用,主要对于数据不能更改。(对指针进行去掉常量性)
#include<iostream> using namespace std; const int * Search(const int * a, int n, int val); int main() { int a[10] = {0,1,2,3,4,5,6,7,8,9}; int val = 5; int *p; p = const_cast<int *>(Search(a, 10, val)); if(p == NULL) cout<<"Not found the val in array a"<<endl; else cout<<"hvae found the val in array a and the val = "<<*p<<endl; return 0; } const int * Search(const int * a, int n, int val) { int i; for(i=0; i<n; i++) { if(a[i] == val) return &a[i]; } return NULL; }
对引用去除常量性,
#include<iostream> using namespace std; const int & Search(const int * a, int n, int val); int main() { int a[10] = {0,1,2,3,4,5,6,7,8,9}; int val = 5; int &p = const_cast<int &>(Search(a, 10, val)); if(p == NULL) cout<<"Not found the val in array a"<<endl; else cout<<"hvae found the val in array a and the val = "<<p<<endl; return 0; } const int & Search(const int * a, int n, int val) { int i; for(i=0; i<n; i++) { if(a[i] == val) return a[i]; } return NULL; }