Friend function
friend member function
#include <iostream>
using namespace std;
class A;//当用到友元成员函数时,需注意友元声明与友元定义之间的互相依赖。这是类A的声明
class B{
public:
void dis(int x, A &t);//该函数是类A的友元函数
};
class A{
public:
friend void B::dis(int x, A &t);//声明B中的dis函数为友元成员函数
friend void dis2(A &t);//全局友元函数
private:
int x;
};
void B::dis(int x, A &t){
t.x = x;
cout << t.x << endl;
}
void dis2(A &t){
cout << t.x << endl;
}
int main(){
class A a; class B b;
b.dis(1,a);
dis2(a);
return 0;
}
Operator overloading friend function as a function of the class
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double t,double i){real=t;imag=i;}
friend Complex operator + (Complex &c1, Complex &c2);//重载运算符函数作为友元函数
void display();
private:
double real; double imag;
};
Complex operator + (Complex &c1, Complex &c2)
{ return Complex(c1.real+c2.real, c1.imag+c2.imag); }
void Complex::display()
{ cout<<"("<<real<<","<<imag<<"i)"<<endl; }
int main()
{
Complex c1(3,4),c2(5,-10),c3;
c3 = c1 + c2;//运算符+用于复数运算
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c1+c2=";c3.display();
return 0;
}
Tomomoto类
#include <iostream>
using namespace std;
class A
{
public:
friend class C;//友元类的声明
private:
int data;
};
class C//C是A的友元类,类C的所有成员函数都是类A的友元函数,可以访问类A的私有成员和保护成员
{
public:
void set_show(int x, A &a) { a.data = x; cout << a.data << endl; }
};
int main(void)
{
class A a;
class C c;
c.set_show(1, a);
return 0;
}