C ++类型的转换,它们正在做什么,哪些变量有效?

时间:2013-04-05 17:44:44

标签: c++ pointers casting

好的,我在理解不同类型的铸件时遇到了一些麻烦,以及它们的用途。我创建了两个类:A和B.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

0 个答案:

没有答案