修改方案一:
#include<iostream>
#include<stdlib.h>
using namespace std;
class C
{private:
int x;
public:
C(int x){this->x = x;}
int getX()const{return x;}
};
int main()
{ const C c(5);
cout<<c.getX();
return 0;
}
修改方案二:
#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()
{ C c(5);
cout<<c.getX();
return 0;
}
这两种方案我更倾向于第一种,这样可以防止普通成员函数修改常对象中数据成员的值。