问题 填空题

以下程序运行后的输出结果是 【10】 #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 0; }

答案

参考答案:stringX stringY

解析: 本题考核友元函数的应用。该程序中,类X的成员函数show()在类Y中说明为类Y的友元函数,因此,在该友元成员show()中可以访问类Y的私有成员stry。成员函数show()的功能就是输出类X的私有成员strx和Y对象ob的私有成员stry。主函数main()中定义了X类的一个对象a和Y类的一个对象b,并且都进行了初始化。然后调用对象a的成员函数show,输出对象a中私有成员strx中的内容和对象b中私有成员stry中的内容,即字符串stringX和stringY。

单项选择题
单项选择题