C++中4种类型转换方式
2017-04-01 21:25
411 查看
C++中4种类型转换方式
首先类型转换,比如以下代码int i; double d = 12.0; i = (int)d;
但是这种强制转换符对于类和类的指针来说,就比较麻烦,所以C++标准定义了四个新的转换符:
reinterpret_cast
static_cast
dynamic_cast
const_cast
reinterpret_cast
转换一个指针为其他类型的指针,也允许一个指针转换为整数类型,反之亦然#include <iostream> using namespace std; class A { public: void hello() { cout << "this is a" << endl; } }; class B { public: void hello() { cout << "this is b" << endl; } }; int main() { A* a = new A; a->hello(); B* b = reinterpret_cast<B *>(a); b->hello(); int c = reinterpret_cast<int>(a); cout << a << endl; cout << c << endl; system("pause"); }
运行结果如下:
static_cast
允许任意的隐式转换和相反转换动作(即使它是不允许隐式的),比如类上,它允许这样两个操作:(1)子类类型的指针转换为父类类型的指针(这个是有效的隐式转换),(2)转换父类的指针为子类指针(隐式操作是不允许的),当然也可以用在基础类型转换上,这里与dynamic_cast做对比#include <iostream> using namespace std; class A { public: void hello() { cout << "this is a" << endl; } }; class B:public A { public: void hello() { cout << "this is b" << endl; } }; int main() { A* a = new A; B* b = new B; //子类转换成父类 A* a1 = static_cast<A *>(b); a1->hello(); //父类转换成子类 B* b1 = static_cast<B *>(a); b1->hello(); system("pause"); }
结果如下:
dynamic_cast
只能用于对象的指针和引用,用于多态的时候允许任意的隐式类型以及反转过程(它这里与static_cast不同的地方就值,在反转过程的时候会检查操作是否有效,无效返回NULL),具体代码如下:#include <iostream> using namespace std; class A { public: virtual void hello() { cout << "this is a" << endl; } }; class B:public A { public: void hello() { cout << "this is b" << endl; } }; int main() { A* a1 = new A; A* a2 = new B; B* b1 = dynamic_cast<B *>(a1); B* b2 = dynamic_cast<B *>(a2); if (b1 != NULL) { cout << "this is b1" << endl; b1->hello(); } if (b2 != NULL) { cout << "this is b2" << endl; b2->hello(); } system("pause"); }
在实现的过程中,发现如果类没有包含多态类型会报错
const_cast
说这个之前先说一下const对象的指针问题const int* p; int a = 10; p = &a; //*p = 20; 不允许 a = 20;
这里说的是p本身可以修改,但是p指向的内容不能通过p来修改
int c=20; int *const p=&c;
而这样定义,则是p本身是const,指向的内容可以修改。
简单一句话来说,const在*后面就是指针本身是const,const在*前面就是指向的内容不允许通过指针修改
而const_cast就是改变这个性质,代码如下
#include <iostream> using namespace std; class A { public: A(int num) { aa = num; } void hello() { cout << "this is a" << endl; } int aa; }; int main() { const A* a = new A(5); cout << a->aa << endl; //a->aa = 20; 不允许 //A* a1 = a; const A* 类型不允许初始化A* A* a2 = const_cast<A*>(a); a2->aa = 30; cout << a->aa << endl; system("pause"); }
运行结果
相关文章推荐
- C++中的4种类型转换方式
- C++中的4种类型转换方式
- 比较C++中的4种类型转换方式
- C++中的4种类型转换方式 cast操作
- C++中的4种类型转换方式
- C++中的4种类型转换方式
- [C++]中4种‘类型转换’方式
- 比较C++中的4种类型转换方式(转自http://blog.csdn.net/hrbeuwhw/article/details/7884797)
- 比较C++中的4种类型转换方式
- 比较C++中的4种类型转换方式
- 比较C++中的4种类型转换方式
- 比较C++中的4种类型转换方式
- C++中的4种类型转换方式 cast操作
- C++中的4种类型转换方式
- C++中4种类型转换方式 cast操作详解
- 比较C++中的4种类型转换方式
- 比较C++中的4种类型转换方式
- 比较C++中的4种类型转换方式
- C++中的4种显示类型转换
- C++类型转换方式总结