Const_cast类型转换符的用法

目录

 

Const_cast类型转换符的用法

Const_cast类型转换符的作用

代码示例


Const_cast类型转换符的用法

Const_cast类型转换符的作用

对const类型的变量用该类型转换符,用于去除变量本身的const限定,使得这个变量可以进行修改。

代码示例

#include <iostream>  
#include <string>  
using namespace std;  
  
class Cstudent  
{  
private:  
    string name;  
    int age;  
public:  
    Cstudent(string name, int age)  
    {  
        this->name = name;  
        this->age = age;  
    }  
    ~Cstudent()  
    {  
        cout << "调用析构函数" << endl;  
    }  
    Cstudent& operator= (const Cstudent& stud)  
    {  
        this->name = name;  
        this->age = age;  
    }  
    void ShowInf()  
    {  
        cout << this->name << "的真实年龄为" << this->age << endl;  
        cout << this->name << "的虚岁为" << ++this->age << endl;  
    }  
};  
  
void Introduction(const Cstudent &stud)  
{  
    // 去除const限定符,使得调用非const函数合法  
    Cstudent& Cstud = const_cast<Cstudent&>(stud); // 最好不要这样做,因为const本来的限定作用就失效了,可能会导致后续程序混乱  
    Cstud.ShowInf();  
    // 下面两句为非法  
    //Cstudent& Cstud = stud;  
    //Cstud.ShowInf();  
}  
  
int main()  
{  
    Cstudent stud("超级霸霸强", 19);  
    Introduction(stud);  
}  

 

我们注意到:

 

通过这句: Cstudent& Cstud = const_cast<Cstudent&>(stud);

在函数中,因为Cstud是stud的引用,因此Cstud和stud两者的地址相同,可以通过去除const限制的Cstud对变量进行修改,但是stud本身还是保持着const类型,准确的来说,我们通过const_cast创建了一个“后门Cstud”,我们可以通过“后门Cstud“去修改const类型对象成员数据的值,但是不能正面通过stud正面修改const类型对象的数据成员的值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥肥胖胖是太阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值