C++中的友元函式
阿新 • • 發佈:2021-10-20
以計算兩點距離為例:
1 class Point 2 { 3 public: 4 Point()= default; 5 Point(float x, float y) :_x(x), _y(y) {} 6 float _x; float _y; 7 }; 8 9 float cal(const Point& s1,const Point& s2) 10 { 11 float x = (s1._x - s2._x) * (s1._x-s2._x); 12 float y = (s1._y - s2._y) * (s1._y-s2._y);13 return sqrt(x+y); 14 15 } 16 17 int main(int argc, char* argv[]) 18 { 19 Point s1(1,2); 20 Point s2(3,4); 21 cout<<cal(s1,s2); 22 return 0; 23 }
由於類Point中的函式全部是public的,所以這裡並無明顯錯誤,如果類Point的成員函式改為private則會出現問題,於是引入友元,解決方案:
1 class Point 2 { 3 public: 4 Point()= default; 5 Point(float x, float y) :_x(x), _y(y) {} 6 private: 7 float _x; float _y; 8 friend float cal(const Point& s1, const Point& s2); 9 }; 10 11 float cal(const Point& s1,const Point& s2) 12 { 13 float x = (s1._x - s2._x) * (s1._x-s2._x); 14 float y = (s1._y - s2._y) * (s1._y-s2._y);15 return sqrt(x+y); 16 17 } 18 19 int main(int argc, char* argv[]) 20 { 21 Point s1(1,2); 22 Point s2(3,4); 23 cout<<cal(s1,s2); 24 return 0; 25 }
由於外部函式不屬於類,故要使得該函式與類產生關係,則需要使用friend。
如果為這個計算函式引入一個管理類,然後使其成為該管理類的成員函式,又該如何,解決如下:
class Point; class Manage { public: Manage() = default; float cal(const Point& s1, const Point& s2); }; class Point { public: Point()= default; Point(float x, float y) :_x(x), _y(y) {} private: float _x; float _y; friend float Manage::cal(const Point& s1, const Point& s2); }; float Manage::cal(const Point& s1, const Point& s2) { float x = (s1._x - s2._x) * (s1._x - s2._x); float y = (s1._y - s2._y) * (s1._y - s2._y); return sqrt(x + y); } int main(int argc, char* argv[]) { Point s1(1,2); Point s2(3,4); Manage a; cout<<a.cal(s1,s2); return 0; }
說明:
類的前向宣告只能說明這是一個類,但是它的大小以及其他屬性一無所知,故只能用於函式的形參、引用及指標。