1. 程式人生 > >【校招面試 之 C++】第4題 拷貝構造函數被調用的3個時機

【校招面試 之 C++】第4題 拷貝構造函數被調用的3個時機

舉例 inf 操作符 -c 接收 clu 分享圖片 his 校招

1、被調用的3個時機:

(1)直接初始化或拷貝初始化;

(2)將一個對象作為一個實參傳遞,形參采用非指針或非引用的對象進行接收時;

(3)函數的返回值是一個非指針或者非對象被接收時。

2、舉例說明:

#include <iostream>
using namespace std;
 
class Test{
private:
	int a;
	int b;
	static int count;
public:
	Test(int i, int j): a(i), b(j){}
	void print();
	Test(Test &t);
	void fun(Test t);
	Test fun1();
};
int Test::count = 1;
void Test::print(){
	cout<<"a = "<<a<<" b = "<<b<<endl;
}

Test::Test(Test & t){
	cout<<"第"<<count++<<"次拷貝構造函數被調用! "<<endl;
	this->a = t.a;
	this->b = t.b;
}

void Test::fun(Test t){										// 關於情形2 需要註意的是:形參不能是引用或者不能是指針的對象
	cout<<"a = "<<t.a<<" b = "<<t.b<<endl;
}

Test Test::fun1(){												// 關於情形3 需要註意的是:返回類型不能是引用或者不能是指針的對象
	this->a = this ->a ++;
	this->b = this->b ++;
	return *this;
}

int main(int argc, char*argv[])
{
        Test t(1,2);
	 // 調用拷貝構造函數 情形1
Test t1(t); // 調用拷貝構造函數 情形2 t1.fun(t); t.print(); // 調用拷貝構造函數 情形3 Test t3 = t1.fun1(); // 註意這種情況不會調用重載賦值操作符 Test t; t = t1這種情況的賦值運算符是會被重載的 t3.print(); system("pause"); return 0; }

輸出結果:

技術分享圖片

【校招面試 之 C++】第4題 拷貝構造函數被調用的3個時機