操作题
1. 请使用VC6或使用【答题】菜单打开
考生文件夹proj1下的工程proj1。其中有线段类Line的定义。程序中位于每个“// ERROR ****found****”之后的一行语句有错误,请加以改正。改正后程序的输出结果应该是:
End point 1 = (1,8),End point 2 = (5,2),length = 7.2111。
注意:只修改每个“// ERROR ****found****”下的那一行,不要改动程序中的其他内容。
#include <iostream>
#include <cmath>
using namespace std;
class Line;
double length(Line);
class Line{ //线段类
double x1,y1; //线段端点1
double x2,y2; //线段端点2
public:
// ERROR *******found*******
Line (double x1, double y1, double x2, double y2) const {
this -> x1 = x1;
this -> y1 = y1;
this -> x2 = x2;
this -> y2 = y2;
}
double getX1() const {return x1;}
double getY1() const {return y1;}
double getX2() const {return x2;}
double getY2() const {return y2;}
void show() const {
cout << "End point 1 = ("<< x1 << "," << y1;
cout << "), End point 2 = ("<< x2 << "," << y2;
// ERROR *******found*******
cout << "), length = " << length (this)
<< "。" << endl;
}
};
double length (Line i) {
// ERROR *******found*******
return sqrt ((1.x1 - 1.x2) * (1.x1 - 1.x2) + (1.y1 - 1.y2) * (1.y1 - 1.y2));
}
int main() {
Line r1(1.0,8.0,5.0,2.0);
r1.show();
return 0;
}
【正确答案】(1)Line(double x1,double y1,double x2,double y2) {
(2)cout << "),length =" << length(* this) << "。" << endl;
(3)return sqrt((l.getX1() - l.getX2()) * (l.getX1() - l.getX2()) + (l.getY1() - l.getY2()) * (l.getY1() - l.getY2()));
【答案解析】[考点] 本题考查Line类,其中涉及构造函数、this指针和const函数。判断一个函数是否为const函数,就要观察该函数体内是否有变量值发生改变,若有变量值发生改变,则该函数不是const函数。一般构造函数不能用const,因为要给私有成员赋初始值。类的私有成员不能被类外函数调用,只能通过成员函数调用。
(1)主要考查考生对构造函数的掌握,构造函数要给私有成员赋初始值,因此不能使用const来限制。
(2)主要考查考生对this指针的掌握,由函数length的声明double length(Line);可知,length函数的形参是Line类,在void show() const函数里,this指针指向的是当前Line类,因此可以用*this表示当前Line类。
(3)主要考查考生对成员函数的掌握,length函数是类外函数,不能直接调用类的私有成员,因此要通过成员函数取得对应的值。
this是指向自身对象的指针,它是一个指针类型,因此要使用标识符“*”来取出它所指向的值。