タイプ変換2:Type casting


C++ is a strong-typed language. There exist two main syntaxes for generic type-casting:functional and c-like:C++は強いタイプの言語です.関数上の&クラスCの2つの主要な汎用タイプ変換構文があります.
double x = 10.3;
int y;
y = int (x);    // functional notation   
y = (int) x;    // c-like cast notation C   

この2つのタイプの変換フォーマットは、ベース・データ・タイプのほとんどのニーズを機能的に満たすのに十分です.しかしながら、これらの操作は、クラスおよびクラスを指すポインタに区別なく使用することができ、構文が正しく記載されているが、実行時エラーを引き起こす可能性がある.次のコードはコンパイル中にエラーがありません.
// class type-casting
#include <iostream>
using namespace std;

class Dummy {
    double i,j;
};

class Addition {
    int x,y;
  public:
    Addition (int a, int b) { x=a; y=b; }
    int result() { return x+y;}
};

int main () {
  Dummy d;
  Addition * padd;
  padd = (Addition*) &d;
  cout << padd->result();
  return 0;
}

Additionタイプのポインタpaddは、それとは無関係のDummyタイプdに向けられている.後続のresultメンバー呼び出しでは、ランタイムエラー/その他の予期せぬ結果が発生します.なぜなら、制限されていない明示的なタイプ変換では、任意のタイプのポインタを他のタイプのポインタに向けることができます.
クラス間のこのタイプの変換を制御するには、dynamic_という4つの特定のタイプの変換操作があります.cast , reinterpret_cast, static_cast, const_cast; 加えて、上記の変換は5種類あります(c-likeの提唱はありません):
dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)
new_type(expression); //             。            ???

dynamic_cast
dynamic_castは、クラスを指すポインタまたは参照(またはvoid*で使用)に使用することができる.この目的は、変換後にポインタが有効な完全なターゲットタイプを指すことを保証することです.ポインタアップ(upcast)変換:converting from pointer-to-derived to pointer-to-base派生クラスポインタをベースクラスポインタ-暗黙変換に変換します.ポインタの下(downcast)への変換:convert from pointer-to-base to pointer-to-derivedベースクラスポインタを派生クラスポインタ(virtualメンバーサポートが必要なマルチステートクラス)に変換します.これは、ポインタ式の有効な完全なターゲットタイプにすぎません.
#include <iostream>
#include <exception>
using namespace std;

class Base { virtual void dummy() {} };
class Derived: public Base { int a; };

int main () {
  try {
    Base * pba = new Derived;
    Base * pbb = new Base;
    Derived * pd;

    pd = dynamic_cast<Derived*>(pba);
    if (pd==0) cout << "Null pointer on first type-cast.
"
; pd = dynamic_cast<Derived*>(pbb); if (pd==0) cout << "Null pointer on second type-cast.
"
; } catch (exception& e) {cout << "Exception: " << e.what();} return 0; }

出力:
Null pointer on second type-cast.

pba&pbbはBase*タイプのポインタです.実際にpbaは派生クラスを指し,pbbはベースクラスを指す.そのため、dynamic_をそれぞれ使用するとcast時(下へ変換)、pbaは完全な派生クラスオブジェクトを指すが、pbbはベースクラスのオブジェクトを指す.したがって、pbbは完全な派生クラスオブジェクトを指すわけではありません.変換が失敗した場合はNULLポインタを返します.dynamic_を使用する場合castは参照タイプを変換し、変換が実行できない場合bad_を放出します.cast異常.
dynamic_cast can also perform the other implicit casts allowed on pointers: casting null pointers between pointers types (even between unrelated classes), and casting any pointer of any type to a void* pointer. dynamic_castでは、nullポインタとポインタ(nullポインタと非nullポインタ)タイプとの間の変換を他の暗黙的に許可します.任意のタイプのポインタをvoid*ポインタに変換します.
static_cast reinterpret_cast const_cast typeid