C++实验03(01)Location类

题目描述
设计一个用来表示直角坐标系的Location类,有两个double型私有数据成员x,y;主程序中,输入相应的值,创建类Location的两个对象a和b,要求a的坐标点在第3 象限,b的坐标点在第2象限;分别采用成员函数和友元函数计算给定两个坐标点之间的距离。
【提示】类Location的参考框架如下:
class Location
{
public:
Location(double a,double b);//构造函数
double getX(); //成员函数,取x坐标的值
double getY(); //成员函数,取y坐标的值
double distance1(Location &);//成员函数,求给定两点之间的距离
//友元函数,求给定两点之间的距离
friend double distance1(Location &,Location&);
private:
double x,y;
};
输入描述
二行,每行分别为一个点的坐标
输出描述
四行:
第一、二行分别为第一个点、第二个点的坐标
第三行为调用成员函数求出的点之间的距离
第四行为调用友元函数求出的点之间的距离
输入样例
1 2
6 7
输出样例
第一个点:A(1,2)
第二个点:B(6,7)
调用成员函数,Distance=7.07107
调用友元函数,Distance=7.07107

#include <iostream>
#include <cmath>

using namespace std;
class Location
{
    
    
public:
	Location(double a, double b);   //构造函数
	double getX();    //成员函数,取x坐标的值
	double getY();    //成员函数,取y坐标的值
	double distance1(Location &);   //成员函数,求给定两点之间的距离	
	friend double distance1(Location &, Location&);	  //友元函数,求给定两点之间的距离
private:
	double x, y;
};
Location::Location(double a, double b)
{
    
    
	x = a;
	y = b;
}
double Location::getX()
{
    
    
	return x;
}
double Location::getY()
{
    
    
	return y;
}
double distance1(Location &a, Location&b)
{
    
    
	double dx = a.getX() - b.getX();
	double dy = a.getY() - b.getY();
	return sqrt(dx*dx + dy * dy);

}
double Location::distance1(Location &b)
{
    
    

	double dx = x - b.getX();
	double dy = y - b.getY();
	return sqrt(dx*dx + dy * dy);

}

int main()
{
    
    
	double x1, x2, y1, y2;
	cin >> x1 >> y1;
	cin >> x2 >> y2;
	Location a(x1, y1);
	Location b(x2, y2);

	cout << "第一个点:" << "A(" << x1 << "," << y1 << ")" << endl;
	cout << "第二个点:" << "B(" << x2 << "," << y2 << ")" << endl;

	cout << "调用成员函数,Distance=" << a.distance1(b) << endl;
	cout << "调用友元函数,Distance=" << distance1(a, b) << endl;
	return 0;
}

成员函数与友元函数

成员函数
double Location::distance1(Location &b)
{

	double dx = x - b.getX();
	double dy = y - b.getY();
	return sqrt(dx*dx + dy * dy);

}

使用
a.distance1(b)
友元函数

友元函数不用写作用域范围

double distance1(Location &a, Location&b)
{
	double dx = a.getX() - b.getX();
	double dy = a.getY() - b.getY();
	return sqrt(dx*dx + dy * dy);

}
使用
distance1(a, b)

猜你喜欢

转载自blog.csdn.net/weixin_44179485/article/details/105754170