const_cast的应用

对于const变量,我们不能修改它的值,这是这个限定符最直接的表现。但是我们就是想违背它的限定希望修改其内容怎么办呢?于是我们可以使用const_cast转换符是用来移除变量的const限定符。
const_cast类型转换能够剥离一个对象的const属性,也就是说允许你对常量进行修改。

#include<iostream>
using namespace std;

/*
用法:const_cast<type_id> (expression)
  该运算符用来修改类型的const或volatile属性。除了const 或volatile修饰之外, type_id和expression的类型是一样的。
  一、常量指针被转化成非常量指针,并且仍然指向原来的对象;
  二、常量引用被转换成非常量引用,并且仍然指向原来的对象;
  三、常量对象被转换成非常量对象。 
  type_id 必须为指针或引用
*/

class B
{
public:
    int m_iNum;
    B() : m_iNum(50)
    {   }
};

void foo()
{
    const B *b1 = new B();
    //b1->m_iNum = 100;          // 编译错误
    // 做如下转换,体现出转换为指针类型
    B *b2 = const_cast<B*>(b1);
    b2->m_iNum = 200;
    cout<<"b1: "<< b1->m_iNum <<endl;
    cout<<"b2: "<< b2->m_iNum <<endl;

    const B b3;
    //b3.m_iNum = 100;     // 编译错误
    B b4 = const_cast<B&>(b3);          // b4是另外一个对象
    b4.m_iNum = 200;
    cout<<"b3: "<<b3.m_iNum <<endl;
    cout<<"b4: "<<b4.m_iNum <<endl;

    const B b5;
    //b5.m_iNum = 100;     // 编译错误

    // 或者左侧也可以用引用类型,如果对b6的数据成员做改变,就是对b5的值在做改变
    B &b6 = const_cast<B&>(b5);
    b6.m_iNum = 200;
    cout<<"b5: "<<b5.m_iNum <<endl;
    cout<<"b6: "<<b6.m_iNum <<endl;
    
    // force to convert 
    const int x = 50;
    int* y = (int *)(&x);       // 同样的地址,但是内容是不一样的
    *y = 200;
    cout << "x: "<<x<<" address: "<<&x<<endl;
    cout << "*y: "<<*y<<" address: "<<y<<endl;
    cout<<endl;
    
    const int xx = 50;
    int* yy = const_cast<int *> (&xx);     // 同样的地址,但是内容是不一样的
    *yy = 200;
    cout << "xx: "<<xx<<" address: "<<&xx<<endl;
    cout << "*yy: "<<*yy<<" address: "<<yy<<endl;
    cout<<endl;
    // int
    const int xxx = 50;
    int yyy = const_cast<int&> (xxx);     // yyy是另外一个int对象
    yyy = 200;
    cout << "xxx: "<<xxx<<" address: "<<&xxx<<endl;
    cout << "yyy: "<<yyy<<" address: "<<&yyy<<endl;
}

int main(void)
{
    foo();
    return 0;
}

运行结果如下:

原文地址:https://www.cnblogs.com/sooner/p/3257083.html