OJ:奇怪的类复制

描述

程序填空,使其输出9 22 5

#include <iostream>
using namespace std;

class Sample {
public:
	int v;
// 在此处补充你的代码
};

void PrintAndDouble(Sample o)
{
	cout << o.v;
	cout << endl;
}

int main()
{
	Sample a(5);
	Sample b = a;
	PrintAndDouble(b);
	Sample c = 20;
	PrintAndDouble(c);
	Sample d;
	d = a;
	cout << d.v;
	return 0;
}

输入

输出

9
22
5

程序填空

Sample(){}
Sample(int i) : v(i){}
Sample(const Sample& s){
	v = s.v + 2;
}

解析:void PrintAndDouble( Sample o) 参数不是引用或指针类型,那么就相当于值传递,函数会构造一个实参的副本。构造这个副本的过程导致复制构造函数被多调用了一次。

原文地址:https://www.cnblogs.com/GyForever1004/p/9107738.html