C++ 科目二 [const_cast]

基础数据类型

const_cast 仅仅是深层拷贝改变,而不是改动之前的值
如果需要使用改动后的值,需要通过指针或者引用来间接使用


const int n = 5;
const string s = "MyString";

// cosnt_cast 针对指针,引用,this指针
// const_cast 仅仅是深层拷贝改变,而不是改动之前的值
int *k = const_cast<int *>(&n);
*k = 123;
cout << n << endl;      // 5
cout << *k << endl;     // 123

int &kRef = const_cast<int &>(n);
kRef = 456;
cout << n << endl;      // 5
cout << kRef << endl;   // 456

不明确

// 在类的非const成员函数中,this的类型为一般形式,即 A * const;
// 在类的const成员函数,this的类型为:const A * const,即指向常量对象的常量指针。

class CTest {
public:
    mutable int m_ntest;
    CTest() : m_ntest(2){};
    void func1(int val) const
    {
        // error: invalid conversion from 'const void*' to 'void*' [-fpermissive]
        // void *p = this;

        // m_ntest = val;
        const_cast(CTest *)(this)->m_ntest = val;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值