C++中四种类型转换符:static_cast、dynamic_cast、reinterpret_cast和const_cast要点解析
1.static_cast
typename dst_ptr = static_cast<typename> (src_ptr)
可用于c++基本類型之間的轉換,子類與派生類之間的指針轉換,類不要求有虛函數。編譯時檢查轉換有效性,不關聯的類指針轉換會在編譯時報錯。與dynamic_cast不同的是指向基類對象的指針也可以轉換為派生類指針,而這種情況是不安全的,dynamic_cast在這種情況會返回NULL,因為派生類指針指向的并不是一個派生類對象。
2.dynamic_cast
typename dst_ptr = dynamic_cast<typename> (src_ptr)
基類必須有虛函數,否則編譯出錯。c++在運行時不關心指針是什么類型的,關心的是指針指向的對象是什么類型的,簡單的一種情況是將基類對象賦值給派生類指針,那么在派生類指針訪問派生類有而基類沒有的方法時就會出現訪問虛函數表崩潰,另外dynamic_cast還支持交叉轉換,如下:
class A{public:int m_iNum;virtual void f(){}};class B:public A{};class D:public A{};void foo(){ B *pb = new B; pb->m_iNum = 100; D *pd1 = static_cast<D *>(pb); //compile error D *pd2 = dynamic_cast<D *>(pb); //pd2 is NULL delete pb; }
dynamic_cast是用的比較多的類型轉換符,不過這個轉換符在轉換的時候有性能問題。
3.reinterpret_cast
typename dst_ptr = reinterpret_cast<typename> (src_ptr)
類似c的強制轉換,不改變指針的值直接進行二進制的復制,不過不能移除const等修飾。
static_cast 和 reinterpret_cast 操作符修改了操作數類型,它們不是互逆的。
static_cast 在編譯時使用類型信息執行轉換,在轉換執行必要的檢測(諸如指針越界計算, 類型檢查)。
4.const_cast
const typename dst_ptr = const_cast<const typename> (src_ptr)
typename dst_ptr = const_cast<typename> (src_ptr)
指針轉換時移除指針的const屬性或者添加非常量指針的const屬性。
5.示例代碼
#include <stdlib.h> #include <stdio.h>class base { public:base() :m_base(1){printf("base\n");}virtual void myself(){printf("m_base\n");} private:int m_base; };class derive:public base { public:derive():m_derive(3),m_base(2){}virtual void myself(){printf("m_derive\n");}virtual void print(){printf("print\n");} private:int m_base;int m_derive; };class other { public:virtual void myself(){} };int main(int argc, char* argv[]) {int count = 0;double score = 0.0;count = static_cast<int>(score);base ptr_base = base();base* ptr_base1 = new base();base* ptr_base2 = new derive();derive* ptr_derive1 = new derive();derive* ptr_derive2 = static_cast<derive *>(new base());//ptr_derive2->print();other* ptr_other1 = new other();//ptr_base1 = static_cast<base *>(ptr_derive1);ptr_derive1 = static_cast<derive *>(ptr_base1);//ptr_other1 = static_cast<other *>(ptr_base1);ptr_base1 = dynamic_cast<base *>(ptr_derive1);ptr_derive1 = dynamic_cast<derive *>(ptr_base1);ptr_other1 = dynamic_cast<other *>(ptr_base1);const base* cptr_base = new base();cptr_base = ptr_base1;ptr_base1 = const_cast<base *>(cptr_base);cptr_base = const_cast<const base *>(ptr_base1);cptr_base = ptr_base1;//ptr_base1 = reinterpret_cast<base *>(cptr_base);ptr_base1 = reinterpret_cast<base *>(ptr_derive1);ptr_base1 = reinterpret_cast<base *>(ptr_other1);return 0; }
6.參考資料
http://blog.chinaunix.net/uid-26548237-id-3954104.html
http://www.cnblogs.com/carsonzhu/p/5251012.html
http://poplars.blog.163.com/blog/static/1394221742013021111210567/
總結
以上是生活随笔為你收集整理的C++中四种类型转换符:static_cast、dynamic_cast、reinterpret_cast和const_cast要点解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最简单的基于FFmpeg的AVfilte
- 下一篇: c++构建工具之shell,config