常量函数形式:int fun(void) const;
注意:const int fun(void) 不是常量函数,只是函数的返回值为常量
#include <iostream>
using namespace std;
class DEMO
{
private:
int a;
public:
DEMO(int a=0):a(a){}
void show ()
{
cout<<"非常量函数:"<<endl;
cout<<a<<endl;
}
void show() const
{
cout<<"常量函数:"<<endl;
cout<<a<<endl;
}
void set(int a)
{
this->a=a;
}
};
int main()
{
DEMO x; //非常量对象
const DEMO y;//常量对象
x.set(20);
x.show();
//y.set(50); y.set必须注释,常量对象在本函数中是无法编译过的,为什么?
y.show();
return 0;
}
执行结果:
非常量函数:20
常量函数:0
对象调用常量函数的规则:
1.非常量对象可以调用非常量函数和常量函数
2.常量对象可以调用常量函数,不可以调用非常量函数
3.常量函数与非常量函数构成重载时,非常量对象调用非常量函数,常量对象调用常量函数
为什么y.set(50)编译不过?
:1常量对象可以调用常量函数,不可以调用非常量函数,即使加个void set(int a) const常量函数也会出错,因为常量函数不能修改成员数据,每个成员函数隐藏了一个指向对象本身的this指针,this指针的类型取决于对象,常对象的this指针是常量指针,常函数无法通过this去修改对象对应的内存
解决方法:
把常量指针this强制转换为非常量指针
加个函数:
void set(int a) const;
{
DEMO*p=const_cast<DEMO*>(this);
p->a=a;
}