在上一篇博客中,我們學(xué)習(xí)了構(gòu)造函數(shù)的作用以及它的用法規(guī)則。現(xiàn)在,我再為大家介紹一種特殊的構(gòu)造函數(shù)。
我們先來(lái)看一段代碼:
#include <iostream>
using namespace std;
class Student
{
public:
Student() { cout << "Student()" << endl; }
private:
string m_strName;
};
int main(void)
{
Student stu1;
Student stu2 = stu1;
Student stu3(stu1);
system("PAUSE");
return EXIT_SUCCESS;
}
我們?cè)陬?lèi)中定義了一個(gè)構(gòu)造函數(shù),并且在調(diào)用的時(shí)候打印一行"Student()"。在main函數(shù)中,我們實(shí)例化了三個(gè)對(duì)象,分別為stu1,stu2,stu3。在實(shí)例化stu2和stu3這兩個(gè)對(duì)象時(shí),我們對(duì)它們用了復(fù)制初始化和直接初始化兩種初始化方法。按之前講的知識(shí)來(lái)說(shuō),運(yùn)行結(jié)果應(yīng)該會(huì)打印出三行"Student()"。但是真實(shí)的運(yùn)行結(jié)果:

我們看到只出現(xiàn)了一行"Student()",也就是說(shuō),構(gòu)造函數(shù)只被調(diào)用了一次。那么可能有人會(huì)問(wèn),這不是與之前講的“對(duì)象實(shí)例化的時(shí)候一定會(huì)調(diào)用構(gòu)造函數(shù)”這個(gè)說(shuō)法相違背了嗎?
其實(shí)這并沒(méi)有違背,它們其實(shí)也調(diào)用了構(gòu)造函數(shù)。只不過(guò)它調(diào)用的不是普通的構(gòu)造函數(shù),而是“拷貝構(gòu)造函數(shù)”。它是在采用直接初始化或復(fù)制初始化實(shí)例化對(duì)象時(shí),被系統(tǒng)自動(dòng)調(diào)用的一種構(gòu)造函數(shù)。
定義拷貝構(gòu)造函數(shù)的方法和普通構(gòu)造函數(shù)有所不同。它的定義格式時(shí):類(lèi)名(const 類(lèi)名& 變量名)。就像這樣:
class Student
{
public:
Student() { cout << "Student()" << endl; }
Student(const Student& stu) { cout << "Student(const Student& stu)" << endl; }
private:
string m_strName;
};
這樣一來(lái),我們就可以看到運(yùn)行結(jié)果打印出了三行文字:

其中通過(guò)后面兩行的文字,我們可以知道調(diào)用了拷貝構(gòu)造函數(shù)。
和普通構(gòu)造函數(shù)一樣,拷貝構(gòu)造函數(shù)沒(méi)有返回值;如果沒(méi)有定義拷貝構(gòu)造函數(shù),系統(tǒng)會(huì)自動(dòng)生成一個(gè)不起任何作用的拷貝構(gòu)造函數(shù);而且在拷貝構(gòu)造函數(shù)后面也是可以跟上初始化列表的。和普通構(gòu)造函數(shù)不同的是,由于拷貝構(gòu)造函數(shù)的參數(shù)是唯一確定的,拷貝構(gòu)造函數(shù)不能進(jìn)行重載。
拷貝構(gòu)造函數(shù)除了在用直接初始化或復(fù)制初始化實(shí)例化對(duì)象的時(shí)候會(huì)被調(diào)用,在參數(shù)傳遞的時(shí)候也會(huì)被調(diào)用。具體是什么意思呢?我們?cè)賮?lái)舉一個(gè)例子:
#include <iostream>
using namespace std;
class Student
{
public:
Student() { cout << "Student()" << endl; }
Student(const Student& stu) { cout << "Student(const Student& stu)" << endl; }
private:
string m_strName;
};
void test(Student s) {}
int main(void)
{
Student stu;
test(stu);
system("PAUSE");
return EXIT_SUCCESS;
}
可以看到,我們?cè)谥虚g加入了一個(gè)叫做test的不進(jìn)行任何操作的函數(shù),里面我們定義了一個(gè)Student類(lèi)的參數(shù)。接下來(lái),在main函數(shù)中實(shí)例化一個(gè)對(duì)象stu,再將這個(gè)對(duì)象傳入剛才定義的函數(shù)中,我們來(lái)看一下運(yùn)行結(jié)果:

可以看到,在調(diào)用了test函數(shù)之后,系統(tǒng)也自動(dòng)調(diào)用了拷貝構(gòu)造函數(shù)。這就是在參數(shù)傳遞時(shí)調(diào)用拷貝構(gòu)造函數(shù)的一個(gè)例子。
以上就是有關(guān)拷貝構(gòu)造函數(shù)的內(nèi)容,在下一篇博客中我將介紹析構(gòu)函數(shù)。