设计点类Point,构造函数自行设计 2.输出点的坐标(普通成员函数),输出点的个数(静态成员函数) 3.计算点到原点之间的距离(友元函数) 4.计算点与原点之间的中点(常函数) 5.用常对象调用中点 6.用常指针实现其它函数的调用 测试该类,运行成功。
时间: 2024-03-13 22:43:35 浏览: 17
好的,我会逐一回答您的问题。
1. 首先,我们来设计点类Point:
```cpp
class Point {
private:
double x, y;
static int count; // 用于统计点的个数
public:
Point(double x = 0, double y = 0); // 构造函数
void show(); // 输出点的坐标
static int getCount(); // 输出点的个数
friend double distance(const Point& a); // 计算点到原点之间的距离
const Point midPoint() const; // 计算点与原点之间的中点
};
```
2. 接下来,我们来实现点类Point的构造函数和输出点的坐标的普通成员函数show(),以及输出点的个数的静态成员函数getCount():
```cpp
Point::Point(double x, double y) {
this->x = x;
this->y = y;
count++;
}
void Point::show() {
cout << "(" << x << ", " << y << ")" << endl;
}
int Point::getCount() {
return count;
}
```
其中,count是用于统计点的个数的静态变量,在构造函数中每次创建新的点对象时加1。
3. 接下来,我们来实现计算点到原点之间的距离的友元函数distance():
```cpp
double distance(const Point& a) {
return sqrt(a.x * a.x + a.y * a.y);
}
```
这里使用了欧几里得距离公式。
4. 再接下来,我们来实现计算点与原点之间的中点的常函数midPoint():
```cpp
const Point Point::midPoint() const {
return Point(x / 2, y / 2);
}
```
这里返回的是一个常对象,即中点。
5. 然后,我们用常对象调用中点函数midPoint():
```cpp
const Point a(3, 4);
a.midPoint().show();
```
输出结果为"(1.5, 2)",表示点(3, 4)与原点之间的中点为(1.5, 2)。
6. 最后,我们用常指针实现其它函数的调用:
```cpp
const Point* p = new Point(1, 2);
p->show();
cout << distance(*p) << endl;
delete p;
```
输出结果为"(1, 2)"和"2.23607",分别表示点(1, 2)的坐标和点(1, 2)到原点之间的距离。
完整的代码如下:
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)