#include "math.h" #include<iostream> using namespace std; class Point { public: Point(double xx, double yy) { x=xx; y=yy; } void Getxy(); friend double Distance(Point &a, Point &b); //類Point的友元函數 friend class Yao; //類Point的友元類 private: double x, y; }; class Yao { public: double Multi(Point &a) { return a.x * a.y + 1; } }; void Point::Getxy() { cout<<"("<<x<<","<<y<<")"<<endl; } double Distance(Point &a, Point &b) //類Point的友元函數 { double dx = a.x - b.x; double dy = a.y - b.y; return sqrt(dx*dx+dy*dy); } int main(void) { Point p1(3.0, 4.0), p2(6.0, 8.0); p1.Getxy(); p2.Getxy(); double d = Distance(p1, p2); //Distance是類Point的友元函數,不是成員函數 cout<<"Distance is "<<d<<endl; Yao yao; d = yao.Multi(p1); cout<<"Math.Multi is "<<d<<endl; return true; }
友元的使用並不復雜,且缺了這玩意完全可以實現,但既然這么設計,就有它存在的合理性,在某些條件下使用它還是很方便的。另外需要注意的一點,編程時,濫用這個東西容易引起數據的安全問題,故需謹慎使用之。