static_cast 用法
語法:
static_cast<type-name>(expression)
僅當 type-name 可以隱式轉換爲 expression 所屬的類型,或者 expression 可以隱式轉換爲 type-name 所屬的類型,轉換纔是合法的。否則,編譯器會報錯。
可以將有繼承關係的派生類對象的地址賦給基類指針。即使基類中沒有虛函數也可以使用 static_cast 進行轉換。
可以將有繼承關係的基類對象的地址賦給派生類指針。因爲派生類指針可以隱式轉換爲基類指針,無需顯式類型轉換,所以可以用 static_cast 進行另一個方向的轉換,即將基類指針轉換爲派生類指針。但是,這樣做有什麼意義呢?
同理,因爲枚舉值可以隱式轉換爲整型,無需顯式類型轉換,所以可以用 static_cast 將整型轉換爲枚舉類型。
如果將沒有繼承關係的對象的地址賦給另一個類的指針,編譯器會報錯。
請看代碼一:
#include<cstdio> class Base{ int dat; public: explicit Base(int val) : dat(val){ printf("%s, this=%p\n", __func__, this); } #if 0 virtual void act(){ #else void act(){ #endif printf("%s, this=%p\n", __func__, this); } }; class Sub : public Base{ public: explicit Sub(int val) : Base(val){ printf("%s, this=%p\n", __func__, this); } }; class Other{ int dat; public: explicit Other(int val) : dat(val){ printf("%s, this=%p\n", __func__, this); } }; int main(){ Base obase(1); Sub osub(2); Base *pbase = NULL; if(pbase = static_cast<Base *>(&osub) ){ pbase->act(); } printf("---------------\n"); Base *ptr = &osub; ptr->act(); printf("---------------\n"); #if 1 if(Sub *psub = static_cast<Sub *>(&obase) ){ psub->act(); } #endif #if 0 Other oother(3); //error: invalid static_cast from type ‘Other*’ to type ‘Base*’ if(pbase = static_cast<Base *>(&oother) ){ pbase->act(); } #endif }
測試結果:
frank@userver:~/project/test/cpp/rtti$ ./a.out
Base, this=0x7fff6d478100
Base, this=0x7fff6d478110
Sub, this=0x7fff6d478110
act, this=0x7fff6d478110
---------------
act, this=0x7fff6d478110
---------------
act, this=0x7fff6d478100
代碼二:
#include<cstdio> int main(){ enum eSource{ eAuxSource = 0, eOpticalSource, eBtSource, eFcSource, eSpotifySource, eGcSource }; #if 0 eSource src = eBtSource; #else //eSource src = 3; //error: invalid conversion from ‘int’ to ‘main()::eSource’ [-fpermissive] eSource src = static_cast<eSource>(3.1); #endif printf("src: %p, %lu, %d\n", &src, sizeof(src), src); }