目录
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类型对象的数据成员的值。