有时候我们却不得不对类内的数据进行修改,但是我们的接口却被声明了const,那该怎么处理呢?我对这个问题的看法如下:
1)标准用法:mutable
class A
{
public:
A(int i=0):test(i) { }
void SetValue(int i)const { test=i; }
private:
mutable int test; file://这里处理!
};
2)强制转换:const_cast
class A
{
public:
A(int i=0):test(i) { }
void SetValue(int i)const
{ const_cast <int>(test)=i; }//这里处理!
private:
int test;
};
3)灵活的指针:int*
class A
{
public:
A(int i=0):test(i) { }
void SetValue(int i)const
{ *test=i; }
private:
int* test; file://这里处理!
};
4)未定义的处理
class A
{
public:
A(int i=0):test(i) { }
void SetValue(int i)const
{ int *p=(int*)&test; *p=i; }//这里处理!
private:
int test;
};
注意,这里虽然说可以这样修改,但结果是未定义的,避免使用!
5)内部处理:this指针
class A
{
public:
A(int i=0):test(i) { }
void SetValue(int i)const
{ ((A*)this)->test=i; }//这里处理!
private:
int test;
};
6)最另类的处理:空间布局
class A
{
public:
A(int i=0):test(i),c('a') { }
private:
char c;
const int test;
};
int main()
{
A a(3);
A* pa=&a;
char* p=(char*)pa;
int* pi=(int*)(p+4);//利用边缘调整
*pi=5; file://此处改变了test的值!
return 0;
}
虽然我给出了6中方法,但是我只是想说明如何更改,但出了第一种用法之外,另外5种用法,我们并不提倡,不要因为我这么写了,你就这么用,否则,我真是要误人子弟了:)