* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱:
* 作者:吳瑕
* 完成日期: 2012年 04月
03日
* 版本號:
*對任務及求解方法的描述部分
* 輸入描述:
* 問題描述:完成求點類中距離的任務
#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){}
//請繼續寫需要的代碼
double getx(){return x;}
double gety(){return y;}
void input();
double Distance1(CPoint p);//成員函數
friend double Distance2(CPoint &p);//友元函數
};
double Distance3(CPoint &p);//一般函數
void CPoint::input() //以x,y 形式輸入座標點
{
char ch;
cout<<"請輸入座標點(格式x,y ):";
while(1)
{
cin>>x>>ch>>y;
if(ch != ',')
{cout<<"輸入格式不對";}
else
break;
}
}
double CPoint::Distance1(CPoint p)//成員函數的實現,Distance1前加CPoint::
//直接訪問私有數據成員,實質是this->x形式,this指針指向p的首地址
{
return (sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)));
}
double Distance2(CPoint &p)//友元函數的實現,Distance1前不加CPoint::,並不是類的成員函數
//不是類的成員函數,卻可以p.hour的形式直接訪問私有數據成員——友元
{
CPoint p1;
cout<<"請輸入一個點:";
p1.input();
return(sqrt((p1.x-p.x)*(p1.x-p.x)+(p1.y-p.y)*(p1.y-p.y)));
}
double Distance3(CPoint &p)//一般函數的實現,Distance1前不加CPoint::
//只能用公共接口p.getx()形式訪問私有數據成員
{
CPoint p1;
cout<<"請輸入一個點:";
p1.input();
double a,b,c,d;
a=p1.getx();
b=p1.gety();
c=p.getx();
d=p.gety();
return (sqrt((a-c)*(a-c)+(b-d)*(b-d)));
}
int main()
{
double distance;
CPoint p(5,4);
CPoint p1(0,0);
distance=p.Distance1( p1);
cout<<"兩點間點的距離爲:"<<distance<<endl;
distance=Distance2(p1);
cout<<"兩點間點的距離爲:"<<distance<<endl;
distance=Distance3(p1);
cout<<"兩點間點的距離爲:"<<distance<<endl;
system("pause");
return 0;
}
運行結果:
上機感言:
1.成員函數的實現,Distance1前加CPoint::
直接訪問私有數據成員,實質是this->x形式,this指針指向p的首地址
2.友元函數的實現,Distance1前不加CPoint::,並不是類的成員函數
不是類的成員函數,卻可以p.hour的形式直接訪問私有數據成員——友元
3.一般函數的實現,Distance1前不加CPoint::
只能用公共接口p.getx()形式訪問私有數據成員