參考1: C++繼承中構造函數、析構函數調用順序及虛函數的動態綁定html
參考2: 構造函數、拷貝構造函數和析構函數的的調用時刻及調用順序ios
參考3: C++構造函數與析構函數的調用順序ide
拷貝構造函數實際上也是構造函數,具備通常構造函數的全部特性,其名字也與所屬類名相同。拷貝構造函數中只有一個參數,這個參數是對某個同類對象的引用。它在三種狀況下被調用:函數
1 #include<iostream> 2 #include <stdio.h> 3 using namespace std; 4 class point 5 { 6 private: 7 int x,y;//數據成員 8 public: 9 point(){cout << "point()" << endl;} 10 point(int xx=0,int yy=0)//構造函數 11 { 12 x=xx; 13 y=yy; 14 cout<<"構造函數被調用"<<endl; 15 } 16 point(point &p);//拷貝構造函數,參數是對象的引用 17 ~point(){cout<<"析構函數被調用"<<endl;} 18 int get_x(){return x;}//方法 19 int get_y(){return y;} 20 }; 21 22 point::point(point &p) 23 { 24 x=p.x;//將對象p的變相賦值給當前成員變量。 25 y=p.y; 26 cout<<"拷貝構造函數被調用"<<endl; 27 } 28 29 void f(point p) 30 { 31 cout<<p.get_x()<<" "<<p.get_y()<<endl; 32 } 33 34 point g()//返回類型是point 35 { 36 printf("*********%s %d\n",__func__, __LINE__); 37 point a(7,33); 38 printf("*********%s %d\n",__func__, __LINE__); 39 return a; 40 } 41 42 int main() 43 { 44 point a(15,22); 45 printf("*********%s %d\n",__func__, __LINE__); 46 point b(a);//構造一個對象,使用拷貝構造函數。 47 printf("*********%s %d\n",__func__, __LINE__); 48 cout<<b.get_x()<<" "<<b.get_y()<<endl; 49 printf("*********%s %d\n",__func__, __LINE__); 50 f(b); 51 printf("*********%s %d\n",__func__, __LINE__); 52 b=g(); 53 printf("*********%s %d\n",__func__, __LINE__); 54 cout<<b.get_x()<<" "<<b.get_y()<<endl; 55 printf("*********%s %d\n",__func__, __LINE__); 56 }
1 #include <iostream> 2 using namespace std; 3 //基類 4 class CPerson 5 { 6 char *name; //姓名 7 int age; //年齡 8 char *add; //地址 9 public: 10 CPerson(){cout<<"constructor - CPerson! "<<endl;} 11 ~CPerson(){cout<<"deconstructor - CPerson! "<<endl;} 12 }; 13 14 //派生類(學生類) 15 class CStudent : public CPerson 16 { 17 char *depart; //學生所在的系 18 int grade; //年級 19 public: 20 CStudent(){cout<<"constructor - CStudent! "<<endl;} 21 ~CStudent(){cout<<"deconstructor - CStudent! "<<endl;} 22 }; 23 24 //派生類(教師類) 25 //class CTeacher : public CPerson//繼承CPerson類,兩層結構 26 class CTeacher : public CStudent//繼承CStudent類,三層結構 27 { 28 char *major; //教師專業 29 float salary; //教師的工資 30 public: 31 CTeacher(){cout<<"constructor - CTeacher! "<<endl;} 32 ~CTeacher(){cout<<"deconstructor - CTeacher! "<<endl;} 33 }; 34 35 //實驗主程序 36 int main() 37 { 38 CPerson person; 39 CStudent student; 40 CTeacher teacher; 41 }