友元函数

来源:互联网 发布:java资格证 编辑:程序博客网 时间:2024/04/28 18:15

测试代码:

#include<iostream>
using namespace std;

class A;

class B{
 int flag;
public:
 B();
 ~B();
 void chang_flag(int i);
 friend void check_flag(A a,B b);
};

class A{
 int flag;
public:
 A();
 ~A();
 void change_flag(int i);
 friend void check_flag(A a,B b);
};

B::B()
{
 cout<<"Have construct B"<<endl;
 flag=0;
}

A::A()
{
 cout<<"Have construct A"<<endl;
 flag=0;
}

B::~B()
{
 cout<<"Have del B"<<endl;
}

A::~A()
{
 cout<<"Have del A"<<endl;
}


void B::chang_flag(int i)
{
 flag=i;
}

void A::change_flag(int i)
{
 flag=i;
}

void check_flag(A a,B b)
{
 if(a.flag||b.flag)
  cout<<"flag is nonezero"<<endl;
 else
  cout<<"flag is zeor"<<endl;
}


int main()
{
 A a;
 B b;
 check_flag(a,b);
 a.change_flag(1);
 check_flag(a,b);
 return 0;
}

 

 

测试结果:

Have construct A
Have construct B
flag is zeor
Have del A
Have del B
flag is nonezero
Have del A
Have del B
Have del B
Have del A
Press any key to continue

 

可见,友元函数调用,会自动调用析构函数一次!

原创粉丝点击