如何修改c++类中const成员函数中的变量

我们知道const成员函数就是为了说明这个函数中的数据成员不能被修改。然而在某些情况下,可以通过两种方法实现修改,如下:

第一种:将需要被修改的数据成员用mutable 关键字进行修饰

#include
using namespace std;

class test
{
    mutable int i;
public:
    test() :i(0) {}
    test(int ii) :i(ii) {}
    int get()const 
    {
        i++;
        return i;
    }
};
int main()
{
    test t(2);
    int m=t.get();
    
}

第二种:我们知道类中的成员函数(静态成员函数除外,因为它不含this指针),都会被悄悄的传递一个this指针(调用这个函数的对象的地址),并且对于const成员函数中的this指针,也是const指针,于是通过转换const_cast<>除去指针常量性,便可以利用指针进行数据成员的修改

#include
using namespace std;

class test
{
     int i;
public:
    test() :i(0) {}
    test(int ii) :i(ii) {}
    int get()const 
    {
        test* p = const_cast(this);
        p->i+=1;
        return i;
    }
};
int main()
{
    test t(2);
    int m=t.get();
    
}

你可能感兴趣的:(c++)