第七週作業2

#include <iostream>

#include"cmath"

using namespace std;

class CPoint  
{
private:  
    double x;  // 橫座標  
    double y;  // 縱座標  
 public: 
    CPoint(double xx = 0,double yy = 0) : x(xx), y(yy){} 
	void Distance1(CPoint p) const;
	friend void Distance2(CPoint &, CPoint &);  //友元函數聲明
	double getX(){return x;}
	double getY(){return y;}
};

void Distance3(CPoint &, CPoint &); //一般函數聲明
 
//用成員函數輸出兩點之間的距離
void CPoint :: Distance1(CPoint p) const      // 兩點之間的距離(一點是當前點,另一點爲參數p)
{
	double d;  
	d = sqrt((p.x - x) * (p.x - x) + (p.y - y) * (p.y - y));
	cout << "用成員函數輸出" << "兩點之間的距離:" << d << endl;
}
//用友元函數輸出兩點之間的距離
void Distance2(CPoint &X, CPoint &Y)
{
	double d;
	d = sqrt((X.x - Y.x) * (X.x - Y.x) + (X.y - Y.y) * (X.y - Y.y));
	cout << "用友元函數輸出" << "兩點之間的距離:" << d << endl;
}
//用普通函數輸出兩點之間的距離
void Distance3(CPoint &a1, CPoint &a2)
{
	double d;
	d = sqrt((a1.getX() - a2.getX()) * (a1.getX() - a2.getX()) + (a1.getY() - a2.getY()) * (a1.getY() - a2.getY()));
	cout << "用普通函數輸出" << "兩點之間的距離:" << d << endl;
}

int main()
{
	CPoint c1(21, 2);
	CPoint c2(5, 18);

    c1.Distance1(c2); 
	Distance2(c1, c2);//調用Distance函數,實參c1,c2是CPoint類對象。
	Distance3(c1, c2);
	system("pause");
	return 0;
}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章