文档详情

C++引用习题讲义.doc

发布:2017-02-12约6.61千字共10页下载文档
文本预览下载声明
01.分析以下程序的执行结果 #includeiostream.h void main() { int a; int b=a; // 变量引用 b=10; couta=aendl; } 解: 本题说明变量引用的方法。b是a的引用,它们分配相同的空间,b的值即为a的值。 所以输出为 a=10。 注意:引用是引入了变量或对明的一个 义词,引用不产生对象的副本。 ----------------------------------------------------------------- 02.分析以下程序的执行结果 #includeiostream.h class Sample { int x; public: Sample(){}; Sample(int a){x=a;} Sample(Sample a){x=a.x+1;} void disp(){coutx=xendl;} }; void main() { Sample s1(2),s2(s1); s2.disp(); } 解: 本题说明类拷贝构造函数的使用方法。Sample类的Sample(Sample a)构造函数是一个拷贝构造函数,将a对象的x值赋给当前对象的x后加1。 所以输出为:x=3。 ----------------------------------------------------- 03.编写程序,调用传递引用的参数,实现两个字符串变量的交换。 例如开始: char *ap=hello; char *bp=how are you?; 交换的结果使得ap和bp指向的内容分别为: ap: how are you? bp: hello 解: 本题使用引用调用(实现由于字符串指针本身就是地址,这里可不使用引用参数,效果是一样的)。 程序如下: #includeiostream.h #includestring.h void swap(char *x,char *y) // 引用作为参数 { char *temp; temp=x;x=y;y=temp; } void main() { char *ap=hello; char *bp=how are you?; coutap:apendl; coutbp:bpendl; swap(ap,bp); coutswap ap,bpendl; coutap:apendl; coutbp:bpendl; } 本程序的执行结果如下: ap:hello bp:hoe are you? swap ap,bp ap:how are you? bp:hello ----------------------------------------------------- 04.设计一个集合类Set,包括将集合置空、添加元素、判断元素是否在集合中、输出集合,以及将集合中元素逆置,另外还有一个拷贝构造函数,并使用一些数据进行测试。 解: Set类包括私有数据成员elems(存放集合元素)、pc(当前元素指针),一个默认构造函数和拷贝构造函数Set(Set s),另有成员函数empty()(将集合置空)、isempty()(判断集合是否为空)、ismemberof()(判断元素是否在集合中)、add()(添加元素)、print()(输出集合)、reverse(将集合中元素置逆)。 本题程序如下: #includeiostream.h #define Max 100 class Set { public: Set(){pc=0;} Set(Set s); // 对象引用作为参数 void empty(){pc=0;} int isempty(){return pc==0;} int ismemberof(int n); int add(int n); void print(); void reverse(); private: int elems[Max]; int pc; }; int Set::ismemberof(int n) { for(int i=0;ipc;i++) if(elems[i]==n) return 1; return 0; } int Set::add(int n) { if(ismemberof(n)) return 1; else if(pcMax) return 0; else { elems[pc++]=n; return 1; } } Set::Set(Set p) { pc=p
显示全部
相似文档