溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

const_cast<type-id>(expression)

發(fā)布時(shí)間:2020-05-24 11:15:57 來源:網(wǎng)絡(luò) 閱讀:372 作者:神ge 欄目:編程語言
//**********************//
類類型
class B{
    public:
        int m_num;
        B():m_num(50){}
};                                                                                                                                     
void foo(void) {

    const B* b1 = new B();
    B* b2 = const_cast<B*>(b1);
    b2->m_num = 200;
    cout <<"b1:" << b1->m_num << endl;//200
    cout <<"b2:" << b2->m_num << endl;//200


    const B b3;
    B b4 = const_cast<B&>(b3);
    b4.m_num = 300;
    cout << "b3:" << b3.m_num << endl;//50
    cout << "b4:" << b4.m_num << endl;//300
}
//************************//
//************************//
基本類型
void foo(){
    const int a = 100;
    int* p1 = const_cast<int*>(&a);
    *p1 = 200;
    cout << *p1 << endl;//200
    cout << a << endl;//100

    const int* p2 = new int(100);
    int* p3 = const_cast<int*>(p2);
    *p3 = 200;
    cout << *p2 << endl;//200                                                   
    cout << *p3 << endl;//200
}
//************************//

你會(huì)發(fā)現(xiàn):

A:可以為基本類型或者類類型;

const A a;隨便怎么修改a都不會(huì)變化

const A* p = new A();去掉p的const屬性后,*p就變化了.


//*****************//
class A{
    public:                                                                     
        A(){
            m_num=1;
        }   
        int m_num;
};
void foo (void){
    A a;
    const A &r = a;
    A a1 = const_cast<A&>(a);
    a1.m_num = 200;
    cout << a1.m_num << endl;//200
    cout << a.m_num << endl;//1
}
//****************//



const_cast<type-id>(expression)中,type-id只能為指針或引用,其他的都錯(cuò),這個(gè)表達(dá)式即可以去除

expression中的const屬性或volatil屬性,還能增加const屬性或者volatil屬性

const int i = 10;

int i1 = const_cast<int>(i) //錯(cuò)誤


增加const屬性與volatil屬性相反.




向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI