一、深拷貝和淺拷貝構造函數總結:
1、兩個特殊的構造函數:
(1)無參構造函數:
沒有參數的構造函數
Class Test
{
public:
Test()
{
//這是一個無參構造函數
}
};
當類中沒有定義構造函數時,編譯器默認提供一個無參構造函數,并且其函數體為空;換句話來說,就是我們在類中,不用我們程序猿自己寫,編譯就自動提供了無參構造函數(只是我們肉眼看不到!)
#include <iostream>
#include <string>
class Test{
//編譯器默認給我們提供了一個無參構造函數,只是我們肉眼看不到
};
int main()
{
Test t;
return 0;
}
結果輸出(編譯時能夠通過的):
root@txp-virtual-machine:/home/txp# g++ test.cpp
root@txp-virtual-machine:/home/txp#
(2)拷貝構造函數:
參數為const class_name&的構造函數
class Test{
public:
Test(const Test& p)
{
}
}
當類中沒有定義拷貝構造函數時,編譯器默認提供了一個拷貝構造函數,簡單的進行成員變量的值賦值
#include <iostream>
#include <string>
class Test{
private:
int i;
int j;
public:
Test(const Test& p)編譯器默認提供這樣操作的
{
i = p.i;
j = p.j;
}
};
int main()
{
Test t;
return 0;
}
輸出結果(編譯可以通過):
root@txp-virtual-machine:/home/txp# g++ test.cpp
root@txp-virtual-machine:/home/txp#