源程序:
#include<iostream>
using namespace std;
class C
{
public:
int x;
C(int x)
{
this -> x = x;
}
int getX()
{
return x;
}
};
void main()
{
C c(5);
cout << c.getX();
system("pause");
}
源程序:
#include<iostream>
using namespace std;
class C
{
public:
int x;
C(int x)
{
this -> x = x;
}
int getX() const
{
return x;
}
};
void main()
{
const C c(5);
cout << c.getX();
system("pause");
}
截图:
上节课听讲不太好···没全听明白···百度了一下错误才找出了两种改法···
不过明白了~
关于倾向哪一种改法的问题···肯定是第二种!!!因为将成员函数也定义成常的会比较保险哈~
(错误主要的原因是const类型的对调用非const类型的方法导致的。
由于const对象在调用成员函数时,会将this指针强制转换成const this指针,它调用成员函数时会去找对应的const Get*函数,而编译器无法将非const类型的Get*函数转换成const类型的Get*函数,因此出现编译错误。
解决方法就是将Get*函数转化为const类型的函数
在对应函数后面加上const关键字
以上是在csdn里一个前辈的教导~)