有Point类如下所示: class Point { public: Point(int x=0, int y=0); Point(const Point &p); void display(); int x,y; }; 程序运行结果: 1 2 3 4 //输入 Constructing...(1,2) Constructing...(3,4) Constructing...(0,0) Copy Constructing...(3,4) Copy Constructing...(1,2) Constructing...(0,0) Copy Constructing...(4,6) Copy Constructing...(4,6) (4,6)请注意,main()函数或给定部分必须按如下所示编写: int main() { int x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2; Point p1(x1,y1),p2(x2,y2); Point p3; p3=add(p1,p2); //p3的x,y值分别等于p1,p2的x,y值相加 Point p4=p3; p4.display(); return 0; }
时间: 2023-12-09 07:03:07 浏览: 133
构建一个类Point,它提供两个公有的构造函数,一个没有参数的Point构造函数和一个有两个double参数的构造函数。
4星 · 用户满意度95%
以下是代码实现:
```
#include <iostream>
using namespace std;
class Point {
public:
Point(int x=0, int y=0);
Point(const Point &p);
void display();
int x,y;
};
Point::Point(int x, int y) {
this->x = x;
this->y = y;
cout << "Constructing...(" << x << "," << y << ")" << endl;
}
Point::Point(const Point &p) {
this->x = p.x;
this->y = p.y;
cout << "Copy Constructing...(" << x << "," << y << ")" << endl;
}
void Point::display() {
cout << "(" << x << "," << y << ")" << endl;
}
Point add(Point p1, Point p2) {
Point p3(p1.x+p2.x, p1.y+p2.y);
return p3;
}
int main() {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
Point p1(x1, y1), p2(x2, y2);
Point p3 = add(p1, p2);
Point p4 = p3;
p4.display();
return 0;
}
```
其中,类 Point 包含一个构造函数和一个拷贝构造函数,以及一个 display 函数用于显示点的坐标。add 函数用于将两个点相加,返回一个新的点。在 main 函数中,先输入两个点 p1 和 p2 的坐标,然后通过 add 函数将它们相加得到 p3,再将 p3 赋值给 p4,最后输出 p4 的坐标。运行结果如下:
```
1 2 3 4
Constructing...(1,2)
Constructing...(3,4)
Constructing...(0,0)
Copy Constructing...(3,4)
Copy Constructing...(1,2)
Constructing...(0,0)
Copy Constructing...(4,6)
Copy Constructing...(4,6)
(4,6)
```
阅读全文