1

以下のコードを検討してください。

#include <iostream>

using namespace std;

class Base{
    int i;
    public:
    virtual bool baseTrue() {return true;}
    Base(int i) {this->i=i;}
    int get_i() {return i;}
    };

class Derived : public Base{
    int j;
    public:
    Derived(int i,int j) : Base(i) {this->j=j;}
    int get_j() {return j;}
    };

int main()
{
    Base *bp;
    Derived *pd,DOb(5,10);

    bp = &DOb;

    //We are trying to cast base class pointer to derived class pointer
    cout << bp->get_i() << endl;
    cout << ((Derived *)bp)->get_j() << endl;**//HERE1**

    pd=dynamic_cast<Derived*> (bp); **//HERE2**
    // If base class is not polymorphic
    //throw error
    //error: cannot dynamic_cast `bp' (of type `class Base*') to
    //type `class Derived*' (source type is not polymorphic)

    cout << pd->get_j() << endl;**//HERE2**

    //Now we try to cast derived Class Pointer to base Class Pointer

    Base *pb;
    Derived *dp,Dbo(50,100);
    dp = &Dbo;


    cout << ((Base *)dp)->get_i() << endl;**//HERE3**
    //cout << ((Base *)dp)->get_j() << endl;
    //throws error Test.cpp:42: error: 'class Base' has no member named 'get_j'

    pb =  dynamic_cast<Base * > (dp); **//HERE4**
    cout << pb->get_i() << endl; **//HERE4**
    //cout << pb->get_j() << endl;
    //throws error Test.cpp:47: error: 'class Base' has no member named 'get_j'


    return 0;
    }

出力

Gaurav@Gaurav-PC /cygdrive/d/Glaswegian/CPP/Test
$ ./Test
5
10
10
50
50

私がキャストしている方法 (Line HERE1 and HERE2 ) & (HERE3 & HERE4), 2つの違いは何ですか? どちらも同じ出力を生成するので、dynamic_cast を使用する理由

4

1 に答える 1

5

dynamic_cast「悪い」ことをしているときに例外をスローするかNULLを返すという点で「安全」です(または、Nawazが言うように、型が十分に悪いため、コンパイラが間違っていることを確認できるため、コンパイルされません)

(Derived *)...フォームは と同様に動作しますが、reinterpret_cast<Derived *>(...)これは「安全ではありません」 - 意味のある結果が得られるかどうかにかかわらず、1 つのポインターを別のポインター型に変換するだけです。それが「ひどく」振る舞うなら、それはあなたの問題です。

あなたはこれを行うことができます:

int x = 4711;

Derived *dp = (Derived *)x; 
cout << dp->get_j(); 

コンパイラは整数のサイズについて少し不満を言うかもしれませんが、それ以外の場合はコードをコンパイルします。ほとんどの場合、まったく実行されませんが、実行された場合、結果はおそらく「有用」ではありません。

于 2013-05-02T13:05:14.527 に答える