设计点类Point,输出点的信息,输出点的个数,计算点到原点的距离,两点之间的距离(友元函数),两点的中点(友元函数)。
时间: 2024-05-30 22:15:50 浏览: 174
#include<iostream>
#include<cmath>
using namespace std;
class Point{
private:
double x,y; //点的横纵坐标
static int count; //点的个数
public:
Point(double a=0,double b=0):x(a),y(b){count++;} //构造函数
void show(){cout<<"("<<x<<","<<y<<")"<<endl;} //输出点的信息
static void showCount(){cout<<"There are "<<count<<" points."<<endl;} //输出点的个数
friend double distance(Point p1,Point p2); //两点之间的距离
friend Point midpoint(Point p1,Point p2); //两点的中点
double distanceToOrigin(){return sqrt(x*x+y*y);} //点到原点的距离
};
int Point::count = 0; //初始化点的个数为0
double distance(Point p1,Point p2){ //友元函数,计算两点之间的距离
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return sqrt(dx*dx + dy*dy);
}
Point midpoint(Point p1,Point p2){ //友元函数,计算两点的中点
double mx = (p1.x + p2.x) / 2;
double my = (p1.y + p2.y) / 2;
return Point(mx,my);
}
int main(){
Point p1(1,2),p2(3,4),p3(5,6);
p1.show();
p2.show();
p3.show();
Point::showCount();
cout<<"Distance from p1 to origin: "<<p1.distanceToOrigin()<<endl;
cout<<"Distance between p1 and p2: "<<distance(p1,p2)<<endl;
cout<<"Midpoint of p1 and p2: ";
midpoint(p1,p2).show();
return 0;
}
阅读全文