C++ 中的強制類型轉換

來源:互聯網
上載者:User

  顯示轉換也成為強制類型轉換(cast),包括以下列名字命名的強制類型轉換操作符:static_cast、dynamic_cast、const_cast、reinterpret_cast。

 

1. const_cast  const_cast<TYPE> (object)

   The const_cast keyword can be used to remove the const or volatile property from an object. The target data type must be the same as the source type, except (of course) that the target type doesn't have to have the same const qualifier. The type TYPE must be a pointer or reference type.

 

 2. static_cast  static_cast<TYPE> (object);

  The static_cast keyword can be used for any normal conversion between types. This includes any casts between numeric types, casts of pointers and references up the hierarchy, conversions with unary constructor, conversions with conversion operator. For conversions between numeric types no runtime checks if data fits the new type is performed. Conversion with unary constructor would be performed even if it is declared as explicit. It can also cast pointers or references down and across the hierarchy as long as such conversion is available and unambiguous. No runtime checks are performed. 

 

3. dynamic_cast  dynamic_cast<TYPE&> (object);  dynamic_cast<TYPE*> (object)

  The dynamic_cast keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast. 

  If you attempt to cast to a pointer type, and that type is not an actual type of the argument object, then the result of the cast will be NULL.

  If you attempt to cast to a reference type, and that type is not an actual type of the argument object, then the cast will throw a std::bad_cast exception.

   用於將基類類型對象的引用或者指標轉換為同一繼承層次中其他類型的引用或者指標。使用指標時,指標必須是有效,為0或者指向一個對象。與其他強制類型轉換不同,它涉及運行時類型檢查。如果綁定到引用或者指標的對象不是目標類型的對象,則dynamic_cast轉換失敗。如果轉換到指標類型的dynamic_cast失敗,則dynamic_cast的結果是0值;如果轉換到參考型別的dynamic_cast失敗,則拋出一個bad_cast類型的異常。

  一般而言,引用或者指標所綁定的對象的類型在編譯時間是未知的,基類的指標可以賦值為指向衍生類別對象,同樣,基類的引用也可以用衍生類別對象初始化,因此dynamic_cast操作符執行的驗證必須在運行時進行。

dynamic_cast

if (Derived *derivedPtr = dynamic_cast<Derived*>(basePtr))
{
        //     use the Derived object to which derivedPtr points
} else{ 
        // BasePtr points at a Base object
        // use the Base object to which basePtr points
    }

void f(const Base &b)
{
    try {
            const Derived &d = dynamic_cast<const Derived&>(b);
            // use the Derived object to which b referred
        } catch (bad_cast) {
            // handle the fact that the cast failed
        }
}

 

4. reinterpret_cast  reinterpret_cast<TYPE> (object);

  The reinterpret_cast operator changes one data type into another. It should be used to cast between incompatible pointer types.

Different operators for different uses

The four casting operators in C++ can be used in different cases, where each is most appropriate:

static_cast is the most useful cast. It can be used to perform any implicit cast. When an implicit conversion loses some information, some compilers will produce warnings, and static_cast will eliminate these warnings. Making implicit conversion through static_cast is also useful to resolve ambiguity or to clarify the conversion presence. It also can be used to call a unary constructor, declared as explicit. It also can be used to cast up and down a class hierarchy, like dynamic_cast, except that no runtime checking is performed.

const_cast is used to apply or remove const or volatile qualifier from a variable.

dynamic_cast is used on polymorphic pointers or references to move up or down a class hierarchy. Note that dynamic_cast performs runtime-checks: if the object's type is not the one expected, it will return NULL during a pointer-cast and throw a std::bad_cast exception during a reference-cast.

reinterpret_cast is used to perform conversions between unrelated types, like conversion between unrelated pointers and references or conversion between an integer and a pointer.

Old-style cast may correspond to static_cast, reinterpret_cast or const_cast, or even a combination of them. This means that none of these casting operators is as powerful as old-style cast.

 

小記:

  1、static_cast不進行錯誤檢查,可以進行的轉換有:數字類型、繼承層次中的指標或引用、聲明為explicit的單形參建構函式。只要用來進行替換編譯器進行的    隱式轉換。

  2、dynamic_cast進行錯誤檢查,可以進行的轉換:繼承層次中的指標或者引用。 

  3、const_cast用來添加或者去掉一個變數的const或者volatile屬性,這個變數必須是指標或參考型別。 

  4、舊時轉型(C風格轉型)有兩種形式:(T) expression 或 T (expression)。兩種形式並無差別,純粹只是小夥考的位置不同。如:

 

class Widget {
public:
  explicit Widget(int size);
}; 
void doSomeWork (const Widget& w);
doSomeWork( Widget(15) );            //舊風格
doSomeWork( static_cast<Widget>(15) );   //新風格 

 

 

   5、const_cast 通常被用來將對象的常量性移除。它也是唯一有此能力的C++ style 轉型操作符。static_cast 用來強迫隱式轉換,例如將 non_const 對象轉換為cosnt 對象(就像條款3所為),但它無法將const轉換為非const。

  6、static_cast 可以將一個derived class對象轉換為base class對象。但static_cast返回一個derived class對象的base class部分的一個副本:

class Window {
pubilc:
    virtual void onResize(){...}
    ...
};
class SpecialWindow: public Window {
public:
    virtual void onResize() {
        static_cast<Window>(*this).onResize(); //Error, 應該為Window::onResize(); 注意優先順序相同、左結合
        //這裡進行SpecialWindow的專屬行為
    }
    ...
}; 

  錯誤的行,實際上對*this並無任何改變。改正後可以正確對*this調用函數,產生改變。(Effective C++ 條款27)

  7、如果可能,盡量避免轉型,特別是在注重效率的代碼中避免dynamic_cast。 

參考:http://www.cppreference.com/wiki/keywords/casting_comparison

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.