问答题 请使用VC6或使用【答题】菜单打开 proj1下的工程proj1,其中有点类Point和线段类Line和主函数main的定义,程序中位于每个“// ERROR ****found****”之后的一行语句有错误,请加以改正。改正后程序的输出应为:
p1=(8,4)p2=(3,5)
注意:只修改两个“// ERROR ****found****”下的那一行,不要改动程序中的其他内容。
#include <iostream>
#include <cmath>
using namespace std;
class Point {
double x, y;
public:
Point (double x = 0.0, double y = 0.0)
// ERROR *******found*******
{x=x; y=y;}
double getX() const {return x;}
double getY() const {return y;}
// ERROR *******found*******
void show() const {cout <<"<<x<<","<<y<<")"}
};
class Line{
Point p1,p2;
public:
Line (Point pt1, Point pt2)
// ERROR *******found*******
{pt1 = p1; pt2 = p2;}
Point getP1() const {return p1;}
Point getP2() const {return p2;}
};
int main() {
Line line (Point(8, 4), Point(3,5));
cout << "p1 =";
line.getP1(). show();
cout << "p2 =";
line.getP2(). show();
cout << endl;
return 0;
}
【正确答案】
【答案解析】(1):x(x),y(y) {}或{this->x=x,this->y=y;}
(2)void show() const {cout<<"("<<x<<","<<y<<")";}
(3):p1(pt1),p2(pt2) {}或{p1=pt1;p2=pt2}
答案考生文件夹 [考点] 本题考查的是Point类和Line类,其中涉及构造函数、const函数和成员函数。构造函数一般使用成员列表初始化,语句最后有个“;”作为结束符。
[解析] (1)主要考查考生对构造函数的掌握,因为形参名和私有成员名称一样,因此不能直接赋值,在这里使用成员列表初始化,也可以使用this指针赋值。
(2)主要考查考生对语句基本语法的掌握,根据语句:void show() const {cout<<"("<<x<<","<<y<<")"}。可看出函数体内并没有“;”作为cout语句的结束符,因此程序错误。
(3)主要考查考生对构造函数的掌握,形参是pt1和pt2,这里写反了,也可以使用成员列表初始化法,可以避免这种错误。