In the declaration, it can be placed in any part of private, public, and protect in the class.
You can declare a top-level function as a friend, you can also declare a function as a friend of another class, and you can declare a class as a friend of another class. The following code case analysis (friend of a class)!
#include <iostream>
using namespace std;
class A{
private:
int a;
friend class B;
};
class B{
private:
int b;
public:void f(){A a;a.a=10;b=20;cout<<"a.a+b="<<a.a+b<<endl;};
};
int main()
{
B b;
b.f();
return 0;
}
- The relationship of friends is one-way, not two-way. If A is declared to be B's friend, it does not mean that B is A's friend.
- Friend relationships are not transitive.
- The friend function is not a member function of the class, but it can access the private and protected members of the class. In a strict sense, this does not conform to the object-oriented principle.
- Therefore, the use of the friend function is controversial and is easily discarded.
Let's take an example of using operator overloading and friend together to implement +&- for complex numbers, see the following code.
#include <iostream>
using namespace std;
//用friend和运算符重载实现复数的加减运算。
//class Complex
class Complex
{
private:
float Real,Image;
public:
//构造函数
Complex(float r=0,float i=0)
{Real=r;Image=i;};
//成员函数show
void Show(int i)
{cout<<"c"<<i<<"="<<Real<<"+"<<Image<<"i"<<endl;}
//friend的声明
friend Complex operator+(Complex &,Complex &);
friend Complex operator-(Complex &,Complex &);
friend Complex operator+(Complex &,float);
};
//函数的定义和操作符的重载
Complex operator+(Complex &c1,Complex &c2)
{
Complex t;
t.Real=c1.Real+c2.Real;
t.Image=c1.Image+c2.Image;
return t;
}
Complex operator-(Complex &c1,Complex &c2)
{
Complex t;
t.Real=c1.Real-c2.Real;
t.Image=c1.Image-c2.Image;
return t;
}
int main(void)
{
//创建对象 并且初始化
Complex c1(25,50),c2(110,200),c3,c4;
c1.Show(1);
c2.Show(2);
c3=c1+c2;
c3.Show(3);
c4=c2-c1;
c4.Show(4);
return 0;
}