测试代码:
#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
可见,友元函数调用,会自动调用析构函数一次!