/*
* 程式的著作權和版本聲明部分
* Copyright (c) 2011, 煙台大學電腦學院學生
* All rights reserved.
* 檔案名稱:
* 作 者: 張傳新
* 完成日期:2012 年04月02 日
* 版 本 號:1.0
* 對任務及求解方法的描述部分
* 輸入描述:
* 問題描述:使用成員函數、友元函數和一般函數的區別
* 程式輸出:
* 問題分析:……
* 演算法設計:……
*/
#include<iostream> #include<cmath> using namespace std; class CPoint { private: double x; // 橫座標 double y; // 縱座標 public: CPoint(double xx=1,double yy=2):x(xx),y(yy){} double Distance1(CPoint p,CPoint q); // 兩點之間的距離 friend double Distance2(CPoint p,CPoint q); //友元函式宣告int getx(){return x;}int gety(){return y;}void input(); //以x,y 形式輸入座標點 void output(); //以(x,y) 形式輸出座標點 };double Distance3(CPoint p,CPoint q); //一般函式宣告 void main() { CPoint a1; CPoint a2; a1.input(); a1.output(); a2.input(); a2.output(); a1.Distance1(a1,a2);Distance2(a1,a2);Distance3(a1,a2);system("pause"); } void CPoint::input() { char a; cout<<"請以“x,y ”形式輸入座標點:"<<endl; cin>>x>>a>>y; if(a!=',') { exit(0); } } //以(x,y) 形式輸出座標點void CPoint::output() { cout<<"("<<x<<","<<y<<")"<<endl; } // 兩點之間的距離(一點是當前點,另一點為參數p) double CPoint::Distance1(CPoint p,CPoint q) //成員函數的實現,Distance1前加CPoint::{ cout<<"兩點的距離為:"<<endl; cout<<sqrt((q.x-p.x)*(q.x-p.x)+(q.y-p.y)*(q.y-p.y))<<endl; return 0; } double Distance2(CPoint p,CPoint q)//友元函數的實現,Distance2前不加CPoint::,並不是類的成員函數{cout<<"兩點的距離為:"<<endl; cout<<sqrt((q.x-p.x)*(q.x-p.x)+(q.y-p.y)*(q.y-p.y))<<endl; return 0; }double Distance3(CPoint p,CPoint q)//只能用公用介面q.getx()形式訪問私人資料成員{ cout<<"兩點的距離為:"<<endl; cout<<sqrt((q.getx()-p.getx())*(q.getx()-p.getx())+(q.gety()-p.gety())*(q.gety()-p.gety()))<<endl; return 0; }
運行結果:
經驗積累:
1.三個版本的求兩點之間的距離的函數,讓我對於這三種函數的使用更加明確。
上機感言:friend函數使兩個“人”之間的關係更加密切。。。