错误程序:
#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;
}
编译结果:
修改:
#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;
}
结果同上。
第一种方法既保证了被保护对象不可修改的特性,又可以访问它的值,显然比第二种好。