问答题

使用VC6打开考生文件夹下的工程test23_3,此工程包含一个源程序文件test23_3.cpp,其中定义了类X和它的友元类Y,但它们的定义并不完整。请按要求完成下列操作,将程序补充完整。 (1)将类X的静态数据成员y初始化为1。请在注释“//**1**”之后添加适当的语句。 (2)完成类Y的构造函数Y(int i,int j)的定义,将参数i赋值给类Y的数据成员,X的对象a中的数据成员x,并且把参数j赋值给类X的数据成员y,请在注释“//**2**”之后添加适当的语句。 (3)完成类Y的成员函数void Display()的定义,将Y的数据成员,X的对象a中的数据成员x和类X的数据成员y按照“x=_,y=_”的形式显示出来(“_”代表一个数字),请在注释“//**3**”之后添加适当的语句。 输出结果如下: x=5,y=l x=6,y=9 x=5,y=9 注意:除在指定位置添加语句之外,请不要改动程序中的其他内容。 源程序文件test23_3.cpp清单如下: include<iostream.h> class X { friend class Y; public: void Set(int i) {x=i;} void Display() { cout<<"x="<<x<<","; cout<<"y="<<y<<endl; } private: int x; static int y; }; class Y { public: Y(int i, int j) void Display(); private: X a; }; //**1** Y::Y(int i, int j) { //**2** } void Y::Display() { //**3** } void main ( ) { X b; b.Set(5); b.Display(); Y c(6,9); c.Display(); b.Display(); }

【参考答案】

(1) int X::y=1; (2) a.x=i; X;;y=j; (3) cout<<"X="<<a......

(↓↓↓ 点击下方‘点击查看答案’看完整答案、解析 ↓↓↓)
热门 试题

问答题
请使用“答题”菜单或从VC6中打开考生文件夹proj1下的工程proj1。此工程包含了类Pets(“宠物”)和主函数main的定义。程序中位于每个 ERRO************found************下的语句行有错,请加以改正。改正后程序的输出结果是:Name: sonny Type: dogName: John Type: dogName: Danny Type: catName: John Type: dog注意:只能修改每个 ERROR************found************下的那一行,不要改动程序中的其他内容。 源程序#include <iostream>using namespace std;enum Pets_type{dog,cat,bird,fish};class Pets{private:char*name:Pets_type type;public:Pets(const char*name= sonny ,Pets_type type=dog);Pets& operator=(const Pets &s);~Pets();void show() const;};Pets::Pets(const char*name,Pets_type type){ 构造函数this->name=new char[strlen(name)+1];strcpy(this->name,name); ERROR************found************type=type;}Pets::~Pets(){ 析构函数,释放name所指向的字符串 ERROR************found************name=’ 0’:}Pets&Pets::operator=(const Pets &s){if(&s==this) return*this; 确保不要向自身赋值delete[]name;name=new char[strlen(s.name)+1]; ERROR************found************strcpy(s.name,this->name);type=S.type;return*this:}void Pets::show() const{couL<< Name: <<name<< Type: ;switch(type){case dog: cout<< dog ;break;case cat: cout<< cat ;break;case bird: cout<< bird ;break;case fish: cout<< fish ;break;}cout<<endl;}int main(){Pets mypet1,mypet2( John ,dog);Pets youpet( Danny ,cat);mypet1.show();mypet2.show();youpet.show();youpet=mypet2;youpet.show();return 0:}