拷貝構造函數:對象之間複製,或者使用一個對象給另外一個初始化時使用。ios
拷貝構造函數特色:也是構造函數,可是,形參列表中必須有一個對本類對象的引用,而且若是有其餘形參必須被初始化。函數
淺拷貝構造函數的特色:簡單來講,淺拷貝構造函數只是將類中成員變量進行簡單的賦值。那麼,若是有指針類型的成員變量,這種拷貝只會將指針指向的空間的地址進行賦值,拷貝後的對象與源對象中的指針只會指向同一個地址,修改其中一個指針指向的變量的值,將會致使另外一個也發生變化。spa
深拷貝構造函數特色:爲了解決淺拷貝構造函數的缺點,能夠使用深拷貝構造函數。在深拷貝構造函數中,爲全部的指針都申請一段新的空間,而後使用間接尋址的方式進行賦值。指針
簡單的一個程序實例( 直接能夠運行, 由於Boy類使用的是淺拷貝構造函數,所以king的名字發生了變化以後,jack的名字也發生變化,可是Dog是深拷貝構造函數,所以即便mala的名字發生了變化,可是braze的名字仍然保持不變)code
#include <iostream> using namespace std; class Boy{ public: Boy(const char* name); Boy(const Boy& b); int modifyName(const char name[]); char* getName(); ~boyName(){ delete boyName; } private: char* boyName; } class Dog( public: Dog(const char* name); Dog(const Dog& d); int modifyName(const char name[]); char* getName(); ~Dog(){ delete dogName; } private: char* dogName; ) Boy::Boy(const char* name){ boyName = new char[strlen(name)+1]; strcpy(boyName, name); } Boy::Boy(const Boy& b){ boyName = b.boyName; } char* Boy::getName(){ return boyName; } int Boy::modifyName(const char name[]){ delete boyName; boyName = new char[strlen(name)+1]; strcpy(boyName, name); } Dog::Dog(const char* name){ dogName = new char[strlen(name)+1]; strcpy(dogName, name); } Dog::Dog(const Dog& d){ dogName = new char[strlen(d.dogName)+1]; strcpy(dogName, d.dogName); } char* Dog::getName(){ return dogName; } int Dog::modifyName(const char name[]){ delete dogName; dogName = new char[strlen(name)+1]; strcpy(dogName, name); } int main(){ Boy jack("Jack"); Dog braze("Braze"); cout<<jack.getName()<<" has a dog "<<braze.getName()<<endl; Boy king(jack); Dog mala(braze); king.modifyName("King"); mala.modifyName("mala"); cout<<king.getName()<<" has a dog "<<mala.getName()<<endl; cout<<"*************** see the first boy and his dog **************"<<endl; cout<<jack.getName()<<" has a dog "<<braze.getName()<<endl; cout<<"Because class Boy uses shallow copy constructor so that the name of the first boy is changed when the second boy has his own name "<<endl; }