#include<iostream>
#include<stdlib.h>
using namespace std;
class C
{
private:
int x;
public:
C(int x){this->x = x;}
int getX(){return x;}
};
int main()
{
const C c(5);
cout<<c.getX();
return 0;
}
原代码中const c是个常对象,是无法访问他的成员函数,只有在把他的成员函数定义成为const函数时才能允许访问,当然去掉const把c'定义成为普通对象也是可以访问的
还有定义完成员函数之后还想改变其中的值,把x定义成为mutable就行,如下是几种改变方式还有运行结果:
#include<iostream>
#include<stdlib.h>
using namespace std;
class C
{
private:
mutable int x;
public:
C(int x){this->x = x;}
int getX()const {
x=3;
return x;
}
};
int main()
{
const C c(5);
cout<<c.getX();
return 0;
}
运行结果:
当然有些挂羊头卖狗肉的感觉