原来的错误程序:
class C
{
private:
int x;
public:
C(int x){this->x = x;}
int getX(){return x;}
};
void main()
{
const C c(5);
cout<<c.getX();
system("pause");
}
修改后的程序一:
#include<iostream>
using namespace std;
class C
{
private:
int x;
public:
C(int x){this->x = x;}
int getX(){return x;}
};
void main()
{
C c(5);//去掉const,常对象不能引用非const型的成员函数
cout << c.getX() << endl;
system("pause");
}
二:
#include<iostream>
using namespace std;
class C
{
private:
int x;
public:
C(int x){this->x = x;}
int getX() const {return x;}//将成员函数声明为const型,定义的常对象才能引用它
};
void main()
{
const C c(5);
cout << c.getX() << endl;
system("pause");
}
经验积累:
1.要分清对象与成员函数之间是否可以调用,常对象中的数据成员为常变量切必须要有初值
2.常对象不能调用该对象的const成员函数,如果将常成员函数声明为const型后就可以了
3.调用关系:1)常对象只能调用const成员函数
2)一般的成员函数可以引用本类中的非const数据成员,也可以修改他们
3)常成员函数只能引用本类中的数据成员(可以使const数据成员,也可以是非const数据成员),而不能修改他们
上机感言:
主要是考察队常对象、常成员函数和常数据成员之间的关系....有点乱