static_cast<>() 類型轉換

Effective C++ 條款27的例子:用static_cast<*this>()代表類型轉換的隱含問題。
ios

轉換以後操做的並不是原有對象,而是一個副本,是一個臨時變量,沒法取地址,右值。函數

code:對象son,子類的虛函數中,強制轉化this爲父類,並調用父類的虛函數,發現並未修改該子類對象的父類部分的成員變量的值,this

#include <iostream>

using namespace std;


class Father {
public:
    Father(int value):a(value){}
    virtual void blink(int value)
    {
        a = value;
    }
    int getA()
    {
        return a;
    }
private:
    int a;
};

class Son:public Father
{
public:
    Son(int value):Father(value), b(value){}
    virtual void blink(int value)
    {
       // Father::blink(value);
        static_cast<Father>(*this).blink(value);
        b = value;
    }
    int getB()
    {
        return b;
    }
private:
    int b;
};


int main()
{
    Son son(1);
    cout<<son.getA()<<"  "<<son.getB()<<endl;

    son.blink(2);
    cout<<son.getA()<<"  "<<son.getB()<<endl;

    return 0;
}

輸出:spa

相關文章
相關標籤/搜索