C++ const函数怎么调用非const函数(转)

C++ const函数怎么调用非const函数

 (2013-03-22 15:10:35)
  分类: 想想专业
如题,这个问题今天困扰了我一个小时。
来自于梦行智科
原因是程序里有个类,之前写好的,类的成员函数几乎全都是const的,之间调用没什么问题,我要把它改造成我需要的,就必须对函数里的变量做修改,这可难受坏了我了,之间有想过用const_cast,但转错了对象C++ <wbr>const函数怎么调用非const函数
在网上摸索了之后,发现转this,再掉非const函数就可以了.

例子:
class test{
public:
test(int _n):n(_n){}
int add_m(int _n) const{
test * th=const_cast(this);
th->n+=_n;
return n;
}
private:
int n;
};
int main()
{
const test tstcon(2);
tstcon.add_m(1);
}

posted on 2016-01-29 09:58  hustfeiji  阅读(1465)  评论(0)    收藏  举报

导航