问答题
使用VC6打开考生文件夹下的工程RevProj14。此工程包含一个源程序文件RevMain14.cpp,但该程序中类的定义有错误。请改正程序中的错误,使它能得到正确结果。 注意,不要改动main函数,不得删行或增行,也不得更改程序的结构。 源程序文件RevMain14.cpp中的程序清单如下: //RevMain14.cpp #include<iostream> #include<math> using namespace std; class Point private: double x; double y; public: Point() void Point(double x1,double y1) x=x1; y=y1; void setvalue(double x,double y) x=x; y=y; double getx () return x; double gety() return y; void print() cout<<"x="<<x<<",y= "<<y<<end1; ~Point() ; class Line private: Point p1; Point p2; double width; public: Line(double x1,double y1,double x2,double y2,double d) :p1(x1,y1),p2(x2,y2) width=d; ~Line() void displength() double 1; 1=sqrt((p1.getx)-p2.getx())*(p1.getx()-p2-getx())+ (p1.gety()-p2.gety())*(p1.gety()-p2.gety())); cout<<"the length of Line is "<<1<<end1; ; int main() Line *p1; Line 1(5,15,25,35,0.5); p1=&1; p1->displength(); return 0;
【正确答案】 正确的类Point的定义如下; class Point { private: double x,y; public: Point () { } Point (double x1, double y1) { x=x1; y=y1; } void setvalue(double x, double y) { this->x=x; // Point::x=x; this->y=y; //Point::y=y; } double getx(){ return x; } double gety(){ return y; } void print () { cout<<"x= "<<x<<",y= "<<y<<end1; } ~Point() {} };
【答案解析】 [解析] 程序中有两处错误。都是在类Point的定义中。 ①C++中类的构造函数没有函数返回类型。所以类Point的重载构造函数首部前不应该有void说明。 ②在成员函数setvalue()中,变量x和y指示不明确,会产生二义性。所以应该使用 this指针或作用域分辨符指明。
提交答案
关闭