填空题
以下程序运行后的输出结果是{{U}} 【14】 {{/U}}。
#include <iostream>
#include <string>
using namespace std;
class Y;
class X
{
int x;
char *strx;
public:
X(int a,char *str)
{
x=a;
strx=new char[strlen(str)+1];
strcpy(strx,str);
}
void show(Y &ob) ;
};
class Y
{
private:
int y;
char *stry;
public:
Y(int b,char *str)
{
y=b;
stry=new char[strlen(str)+1];
strcpy(stry, str);
}
friend void X::show(Y &ob) ;
};
void X::show(Y &ob)
{
cout<<strx<<",";
cout<<ob.stry<<end1;
}
int main()
{
X a(10,"stringX");
Y b(20,"stringY");
a. show (b) ;
return O;
}
【正确答案】
1、stringX,stringY
【答案解析】[解析] 本题考核类的定义和友元函数的应用。
①该程序中,类X的成员函数show()在类Y中说明为友元,因此,在该友元成员 show()中可以访问类Y的私有成员stry。
②成员函数show()的功能就是输出类X的私有成员strx和Y对象ob的私有成员stry。
③主函数中定义了X类的一个对象a和Y类的一个对象b,并且都进行了初始化。然后调用对象a的成员函数show(),输出对象a中私有成员strx中的内容和对象b中私有成员stry中的内容,即字符串stringX和stringy。