The third week of study: Friends

1. Friend function : The friend function of a class can access the private members of the class but not the member functions of the class. And the member functions (including construction, destructor) of one class can be described as friends of another class

#include<iostream>
using namespace std;
class A;  //这里写一个class A,因为下面 B有A* p,
		//必须要指向一个地方

class B{
    
    
	public:
		void add(A* p); //是指针,如果是别的,A就要先定义了
};

class A
{
    
    
	private:
		int temp;
		friend void B::add(A* p); //B的函数可以作为A友元,使用
								//A的private
		friend int max(A a[],int total);
	public:
		A():temp(0){
    
    }; //如果不自定义,可能会出现不好垃圾值
};

void B::add(A* p)
{
    
    
	p->temp+=100;
	cout<<"now temp is "<<p->temp<<endl; 
}

int max(A a[],int total)
{
    
    
	int Max=-1;
	for(int i=0;i<total;i++)
		if(a[i].temp>Max)
			Max=a[i].temp;
	return Max;
}

int main()
{
    
    
	const int T=4;
	A a[T];
	B b;
	for(int i=1;i<=T;i++)
	{
    
    	cout<<"i : "<<i-1<<endl;
		for(int j=0;j<i;j++)
			b.add(&a[i-1]); //传递地址
	}
	cout<<max(a,T)<<endl;
}

result:
Insert picture description here

  1. Friend class : A is a friend class of B, so member functions of A can access private members of B
class A
{
    
    
	....
	friend class C;
	....
};

class C
{
    
    
	public:
		A a1;
		void showtemp(){
    
    
			cout<<"temp is "<<a1.temp<<endl;
		}
};
//A里声明了C为A的friend类,所以C可以访问A的private,
//在C里声明一个A类,然后直接使用
C c;
for(int i=1;i<=T;i++)
{
    
    	cout<<"i : "<<i-1<<endl;
	for(int j=0;j<i;j++)
	{
    
    
		b.add(&a[i-1]);
		c.a1 = a[i-1];   //要先说明C中A类对象
		c.showtemp();
		}
}

result:
Insert picture description here

Friend classes cannot be passed or inherited

Guess you like

Origin blog.csdn.net/ZmJ6666/article/details/108557709