1. 程式人生 > >C++ 拷貝建構函式練習

C++ 拷貝建構函式練習

總時間限制: 

1000ms

 

記憶體限制: 

65536kB

// 在此處補充你的程式碼

描述

程式填空,使其輸出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

樣例輸入

None

樣例輸出

9
22
5

來源

Guo Wei
 

執行外部函式時,實際上呼叫了拷貝建構函式

#include <iostream>
using namespace std;
class Sample {
public:
	int v;
	// 在此處補充你的程式碼
	Sample(int v_):v(v_){}
	Sample(){}
	Sample(const Sample & s)
	{
		v = s.v + 2;
	}
};
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;
}