设为首页 加入收藏

TOP

3.2.2 填空题(2)
2013-10-07 16:20:25 来源: 作者: 【 】 浏览:71
Tags:3.2.2 填空

3.2.2  填空题(2)

【例3.10】以下程序的执行结果是      。

  1. #include <iostream.h> 
  2. class Sample  
  3. {   int n;  
  4. public:  
  5.     Sample(int i) { n=i; }  
  6.     void add1(Sample s)  
  7.     {   s.n+=n;  }  
  8.     void add2(Sample &s)  
  9.     {   s.n+=n;  }  
  10.     void disp() { cout << "n=" << n << endl; }  
  11. };  
  12. void main()  
  13. {   Sample s1(1),s2(2),s3(3);  
  14.     cout << "s1:";s1.disp();  
  15.     cout << "s2:";s2.disp();  
  16.     s3.add1(s1);  
  17.     s3.add2(s2);  
  18.     cout << "s1:";s1.disp();  
  19.     cout << "s2:";s2.disp();  
  20. }  

解:该程序中Sample类的成员函数add1和add2均以类对象作为参数,add2的参数是对象引用,所以该成员函数被调用后改变实参的值。程序执行结果如下:
 

  1. s1:1  
  2. s2:2  
  3. s1:1  
  4. s2:5  

【例3.11】以下程序的执行结果是      。

  1. #include<iostream.h>   
  2. class Sample  
  3. {   int x;  
  4. public:  
  5.     Sample() {}  
  6.     Sample(int a) {   x=a;  }  
  7.     Sample(Sample &a) {   x=(a.x++)+10;  }  
  8.     void disp() {   cout << "x=" << x << endl;  }  
  9. };  
  10. void main()  
  11. {   Sample s1(2),s2(s1);  
  12.     s1.disp();  
  13.     s2.disp();  
  14. }  

解:Sample类的Sample(Sample &a)构造函数是一个拷贝构造函数,将a对象的x增1,然后加上10后赋给当前对象的x,由于a是引用对象,所以程序执行结果如下::

  1. x=3         //++运算的结果  
  2. x=12        //2+10  

【例3.12】以下程序的执行结果是      。

  1. #include<iostream.h>   
  2. class Sample   
  3. {   int x,y;  
  4. public:   
  5.     Sample() {   x=y=0;}  
  6.     Sample(int i,int j) {   x=i;y=j;  }  
  7.     void copy(Sample &s);  
  8.     void setxy(int i,int j) {   x=i;y=j;  }  
  9.     void print() {   cout<<"x="<<x<<",y="<<y<<endl;  }  
  10. };  
  11. void Sample::copy(Sample &s)  
  12. {   x=s.x;y=s.y;  }  
  13. void func(Sample s1,Sample &s2)  
  14. {   s1.setxy(10,20);  
  15.     s2.setxy(30,40);  
  16. }  
  17. void main()   
  18. {   Sample p(1,2),q;  
  19.     q.copy(p);  
  20.     func(p,q);  
  21.     p.print();  
  22.     q.print();  
  23. }  

解:Sample类中的copy()成员函数进行对象拷贝。在main()中先建立对象p和q,p与q对象的x,y值相同,调用func()函数,由于第2个参数为引用类型,故实参发生改变;而第1个参数不是引用类型,实参不发生改变。程序执行结果如下:

  1. x=1,y=2 
  2. x=30,y=40 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇3.2.2 填空题(1) 下一篇3.2.3 判断题

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·用 Python 进行数据 (2025-12-25 15:49:09)
·如何学习Python数据 (2025-12-25 15:49:07)
·利用Python进行数据 (2025-12-25 15:49:04)
·Java 学习线路图是怎 (2025-12-25 15:19:15)
·关于 Java 学习,有 (2025-12-25 15:19:12)