3.2.2 填空题(2)
【例3.10】以下程序的执行结果是 。
- #include <iostream.h>
- class Sample
- { int n;
- public:
- Sample(int i) { n=i; }
- void add1(Sample s)
- { s.n+=n; }
- void add2(Sample &s)
- { s.n+=n; }
- void disp() { cout << "n=" << n << endl; }
- };
- void main()
- { Sample s1(1),s2(2),s3(3);
- cout << "s1:";s1.disp();
- cout << "s2:";s2.disp();
- s3.add1(s1);
- s3.add2(s2);
- cout << "s1:";s1.disp();
- cout << "s2:";s2.disp();
- }
解:该程序中Sample类的成员函数add1和add2均以类对象作为参数,add2的参数是对象引用,所以该成员函数被调用后改变实参的值。程序执行结果如下:
- s1:1
- s2:2
- s1:1
- s2:5
【例3.11】以下程序的执行结果是 。
- #include<iostream.h>
- class Sample
- { int x;
- public:
- Sample() {}
- Sample(int a) { x=a; }
- Sample(Sample &a) { x=(a.x++)+10; }
- void disp() { cout << "x=" << x << endl; }
- };
- void main()
- { Sample s1(2),s2(s1);
- s1.disp();
- s2.disp();
- }
解:Sample类的Sample(Sample &a)构造函数是一个拷贝构造函数,将a对象的x增1,然后加上10后赋给当前对象的x,由于a是引用对象,所以程序执行结果如下::
- x=3 //++运算的结果
- x=12 //2+10
【例3.12】以下程序的执行结果是 。
- #include<iostream.h>
- class Sample
- { int x,y;
- public:
- Sample() { x=y=0;}
- Sample(int i,int j) { x=i;y=j; }
- void copy(Sample &s);
- void setxy(int i,int j) { x=i;y=j; }
- void print() { cout<<"x="<<x<<",y="<<y<<endl; }
- };
- void Sample::copy(Sample &s)
- { x=s.x;y=s.y; }
- void func(Sample s1,Sample &s2)
- { s1.setxy(10,20);
- s2.setxy(30,40);
- }
- void main()
- { Sample p(1,2),q;
- q.copy(p);
- func(p,q);
- p.print();
- q.print();
- }
解:Sample类中的copy()成员函数进行对象拷贝。在main()中先建立对象p和q,p与q对象的x,y值相同,调用func()函数,由于第2个参数为引用类型,故实参发生改变;而第1个参数不是引用类型,实参不发生改变。程序执行结果如下:
- x=1,y=2
- x=30,y=40