友元是可以访问类的私有成员和保护成员的外部函数。由 friend 修饰,不是本类的成员函数,但是在它的函数体中可以通过对象名访问本类的私有和保护成员。
友元关系不可传递,且是单向的。
友元函数:声明为友元的一般函数或是另一个类的成员函数;
友元类:友元类的所有成员函数都是某个类的友元函数。应用场景较少。
1、友元函数
应用于运算符重载多一些。
#include <iostream> #include <cmath> using namespace std; //友元函数举例 class Point { public: Point(int xx = 0, int yy = 0) { X = xx; Y = yy; } int GetX() { return X; } int GetY() { return Y; } friend float fDist(Point &a, Point &b); private: int X, Y; }; //友元函数的实现 float fDist(Point &p1, Point &p2) { //通过对象访问私有数据成员 double x = double(p1.X - p2.X); double y = double(p1.Y - p2.Y); return float(sqrt(x*x + y*y)); } void main() { Point myp1(1, 1), myp2(4, 5); cout << "The distance is: "; cout << fDist(myp1, myp2) << endl; system("pause"); }
2、友元类
应用较少,了解即可。
#include <iostream> using namespace std; class A { public: friend class B;//在 B类中可以访问 A类 的私有成员、私有函数。 // 友元类声明的位置和 public/private 没有关系。 friend void modifyA(A *pA, int _a); //该函数是 类A 的好朋友 A(int a=0, int b=0) { this->a = a; this->b = b; } int getA() { return this->a; } private: int a, b; }; void modifyA(A *pA, int _a) { pA->a = _a; } //友元类使用场景较少 class B { public: void Set(int a) { Aobject.a = a; } void printB() { cout << Aobject.a << endl; } private: A Aobject; }; void main() { A a1(1, 2); cout << a1.getA() << endl; modifyA(&a1, 100); cout << a1.getA() << endl; B b1; b1.Set(300); b1.printB(); system("pause"); }