使用VC6打开考生文件夹下的工程RevProj11。此工程包含一个源程序文件RevMain11.cpp,但在源程序文件中有错误。请改正程序中的错误,使它能得到正确结果。
注意,不得删行或增行,也不得更改程序的结构。
源程序文件RevMainll.cpp中的程序清单如下:
//RevMainll.cpp
#include<iostream>
using namespace std;
class point
private:
const int color;
int x;
int y;
public:
point(int x,int y,int c)
this->x=x;
this->y=y;
color=c;
void show()
cout<<"x="<<x<<",y="<<y<<",color="<<color<<end1;
;
int main()
const point p(10,10,100);
p.show();
return 0;
参考答案:正确的程序代码如下:
#include<iostream>
using namespace std;
class point
{
private:
const int color;
int x;
int y;
public:
point(int x,int y,int c):color(c)
{
this->x=x;
this->y=y;
}
void show()
{
cout<<"x="<<x<<",y="<<y<<",color="<<color<<end1;
}
};
int main()
{
point p(10,10,100);
p.show();
return 0;
}
解析: 本题程序中有2处错误:
①C++中,如果在一个类中说明了常数据成员,那么构造函数就只能通过初始化列表对数据成员进行初始化。私有成员color被定义成常数据成员,因此构造函数point()对color的初始化形式是错误的。
②C++中,如果将一个对象说明为常对象,则通过该常对象只能调用它的常成员函数,不能调用其他成员函数。主函数中对象p被定义成类point的常对象,因此通过该对象不能调用非常成员函数show()。