打印本文 打印本文  关闭窗口 关闭窗口  
二级模拟试题:C++习题与解析(友元-02)
作者:佚名  文章来源:不详  点击数  更新时间:2008/4/18 16:08:08  文章录入:杜斌  责任编辑:杜斌

02.分析以下程序的执行结果
#include
class B;
class A
{
int i;
public:
int set(B&);
int get(){return i;}
A(int x){i=x;}
};
class B
{
int i;
public:
B(int x){i=x;}
friend A;
};
int A::set(B &b) // 由于使用了类B的定义,故本函数的定义应放在类B定义之后
{
return i=b.i;
}
void main()
{
A a(1);
B b(2);
cout<a.set(b);
cout<}

解:
本题说明友元类的使用方法。这里将类A设置为类B的友元类,因此,类A的所有成员函数均为类B的友元函数。通过调用a.set(b)将b对象的i值赋给a对象的i值。 来源:www.examda.com
所以输出为:1,2
打印本文 打印本文  关闭窗口 关闭窗口