0

わかりました、さまざまなタイプのキャスティングと、それらで何が起こっているのかを理解するのに苦労しています。A と B の 2 つのクラスを作成しました。B は A から派生したものです。

私はたくさんのポインターを作り、それらを画面にぶつけました。何が起こっているのか、どの変数が実際に有効なのかを理解する助けが必要です。

コードは次のとおりです。

#include <iostream>

using namespace std;


class A {
public:
    A(int iValue){
            m_iValue = iValue;
    }

    A(){
            m_iValue = 10;
    }

    virtual void doSomething(){
            cout << "The value is " << getValue() << endl;
    }

    void doSomethingElse(){
            cout << "This is something else" << endl;
    }

    virtual int getValue(){
            return m_iValue;
    }

private:
    int m_iValue;
};

class B : public A{

public:
 B() : A(5){

    }

    virtual void doSomething(){

            cout << "This time, the value is " << getValue() << endl;
    }

    void doSomethingElse(){

            cout << "This is something else entirely" << endl;
    }

    virtual void doAnotherThing(){

            cout << "And this is a third thing" << endl;
    }
};


int main(int argc, char * argv[]){
    A * pA1 = new B;
    A * pA2 = new A;

    B * pB1;
    B * pB2;

    pB1 = (B*)pA1;
    pB2 = (B*)pA2;

    cout << "Step 1 - c style cast:" << endl;
    cout << "  pA1 cast to pointer pB1: " << pB1 << endl;
    cout << "  pA2 cast to pointer pB2: " << pB2 << endl << endl;

    B * pB3;
    B * pB4;

    pB3 = dynamic_cast<B*>(pA1);
    pB4 = dynamic_cast<B*>(pA2);

    cout << "Step 2 - dynamic_cast:" << endl;
    cout << "  pA1 cast to pointer pB3: " << pB3 << endl;
    cout << "  pA2 cast to pointer pB4: " << pB4 << endl << endl;


    B * pB5;
    B * pB6;

    pB5 = static_cast<B*>(pA1);
    pB6 = static_cast<B*>(pA2);

    cout << "Step 3 - static_cast:" << endl;
    cout << "  pA1 cast to pointer pB5: " << pB5 << endl;
    cout << "  pA2 cast to pointer pB6: " << pB6 << endl << endl;

    B * pB7;
    B * pB8;

    pB7 = reinterpret_cast<B*>(pA1);
    pB8 = reinterpret_cast<B*>(pA2);

    cout << "Step 4 - reinterpret_cast:" << endl;
    cout << "  pA1 cast to pointer pB7: " << pB7 << endl;
    cout << "  pA2 cast to pointer pB8: " << pB8 << endl << endl;

    return 0;
}

出力されるものは次のとおりです。

Step 1 - c style cast:
  pA1 cast to pointer pB1: 0x1853010
  pA2 cast to pointer pB2: 0x1853030

Step 2 - dynamic_cast:
  pA1 cast to pointer pB3: 0x1853010
  pA2 cast to pointer pB4: 0

Step 3 - static_cast:
  pA1 cast to pointer pB5: 0x1853010
  pA2 cast to pointer pB6: 0x1853030

Step 4 - reinterpret_cast:
  pA1 cast to pointer pB7: 0x1853010
  pA2 cast to pointer pB8: 0x1853030
4

0 に答える 0