C++有四種類型轉換操作符:static_cast、const_cast、dynamic_cast、reinterpret_cast。
1>. static_cast普通轉換,如double轉int:
1 double a = 10;
2 int b = static_cast<int>(a);
|
2>. const_cast改變const或者volatile屬性:
1 const char* szA = "test";
2 char* szB = const_cast<char*>(szA);
3>. dynamic_cast把指向基類的指針或引用轉換成指向派生類或者基類的兄弟類的指針或引用:
1 class Base
2 {
3 public:
4 virtual void test(){} //基類必須有虛函數
5 };
6
7 class Child : public Base
8 {
9 public:
10 void print(){ cout << "child::base" << endl; }
11 };
12
13 Base* pBase = new Base();
14 Child* pChild = dynamic_cast<Child*>(pBase);
15 pChild->print();
|
4>. reinterpret_cast用來在函數指針之間進行類型轉換
1 typedef void (*FuncPtr)();
2 FuncPtr funcPtrArray[10];
3 int doSomeing(){return 0;}
4
5 funcPtrArray[0] = reinterpret_cast<FuncPtr>(&doSomeing);
posted @
2011-03-07 14:28 郭小帥 閱讀(336) |
評論 (0) |
編輯 收藏