一、实验目的:通过类的设计与实现,将所学知识点综合应用。 1.类的设计与定义,构造函数等。 2.静态成员,友元,常引用等 二、实验要求: 1.设计点类Point,构造函数自行设计 2.输出点的坐标(普通成员函数),输出点的个数(静态成员函数) 3.计算点到原点之间的距离(友元函数) 4.计算点与原点之间的中点(常函数) 5.用常对象调用中点 6.用常指针实现其它函数的调用 测试该类,运行成功。 点类Point的设计图如下: Point int x; int y; static int count=0; //统计点的个数 Point(int x =0,int y=0); int getX(); //得到x int getY(); //得到y void display(); //输出x,y Point midpoint(int x,int y) const;//两点举例 static void showCount(); //输出个数 friend double distance();//求出点到原点的距离
时间: 2024-03-03 20:53:13 浏览: 173
好的,这是您需要的代码:
```c++
#include <iostream>
#include <cmath>
class Point {
private:
int x;
int y;
static int count; // 统计点的个数
public:
Point(int x = 0, int y = 0) {
this->x = x;
this->y = y;
count++;
}
int getX() const {
return x;
}
int getY() const {
return y;
}
void display() const {
std::cout << "(" << x << ", " << y << ")" << std::endl;
}
static void showCount() {
std::cout << "There are " << count << " points." << std::endl;
}
Point midpoint(int x, int y) const {
Point m((this->x + x) / 2, (this->y + y) / 2);
return m;
}
friend double distance(const Point& p);
};
int Point::count = 0;
double distance(const Point& p) {
return sqrt(p.x * p.x + p.y * p.y);
}
int main() {
const Point p1(1, 2);
const Point p2(3, 4);
p1.display();
p2.display();
Point::showCount();
std::cout << "Distance from p1 to origin: " << distance(p1) << std::endl;
std::cout << "Midpoint between p1 and origin: ";
p1.midpoint(0, 0).display();
std::cout << "Midpoint between p1 and p2: ";
p1.midpoint(p2.getX(), p2.getY()).display();
const Point* pp = &p1;
pp->display();
return 0;
}
```
输出如下:
```
(1, 2)
(3, 4)
There are 2 points.
Distance from p1 to origin: 2.23607
Midpoint between p1 and origin: (0, 1)
Midpoint between p1 and p2: (2, 3)
(1, 2)
```
阅读全文