今天审核题库,发现了一个很有趣的问题,拿来分享。
#include<iostream>
using namespace std;
class Sample {
public:
int x;
public:
Sample(){};
Sample(int a){
x=a;
}
Sample(Sample &a){
x=a.x++ +10;
}
void disp(){
cout<<"x="<<x<<endl;
}
};
int main() {
Sample s1(2),s2(s1);
s1.disp();
s2.disp();
return 0;
}
程序输出结果为:3,12。
分析:
- 实例化s1之后,s1.x = 2。
- 实例化s2之后,调用拷贝构造函数,s1.x = 3;
- 由于“先用后增”,s2.x = 12。
注:拷贝构造函数传递的参数是同类型对象的引用,一般需要用const关键字修饰的,避免传递的参数被修改。
感谢偶尔e网事补充