對象是由「底層向上」開始構造的,當創建一個對象時,首先調用基類的構造函數,而後調用下一個派生類的構造函數,依次類推,直至到達派生類次數最多的派生次數最多的類的構造函數爲止。由於,構造函數一開始構造時,老是要調用它的基類的構造函數,而後纔開始執行其構造函數體,調用直接基類構造函數時,若是無專門說明,就調用直接基類的默認構造函數。在對象析構時,其順序正好相反。 ios
#include<iostream> using namespace std; class point { private: int x,y;//數據成員 public: point(int xx=0,int yy=0)//構造函數 { x=xx; y=yy; cout<<"構造函數被調用"<<endl; } point(point &p);//拷貝構造函數,參數是對象的引用 ~point(){cout<<"析構函數被調用"<<endl;} int get_x(){return x;}//方法 int get_y(){return y;} }; point::point(point &p) { x=p.x;//將對象p的變相賦值給當前成員變量。 y=p.y; cout<<"拷貝構造函數被調用"<<endl; } void f(point p) { cout<<p.get_x()<<" "<<p.get_y()<<endl; } point g()//返回類型是point { point a(7,33); return a; } void main() { point a(15,22); point b(a);//構造一個對象,使用拷貝構造函數。 cout<<b.get_x()<<" "<<b.get_y()<<endl; f(b); b=g(); cout<<b.get_x()<<" "<<b.get_y()<<endl; }
#include <iostream> using namespace std; //基類 class CPerson { char *name; //姓名 int age; //年齡 char *add; //地址 public: CPerson(){cout<<"constructor - CPerson! "<<endl;} ~CPerson(){cout<<"deconstructor - CPerson! "<<endl;} }; //派生類(學生類) class CStudent : public CPerson { char *depart; //學生所在的系 int grade; //年級 public: CStudent(){cout<<"constructor - CStudent! "<<endl;} ~CStudent(){cout<<"deconstructor - CStudent! "<<endl;} }; //派生類(教師類) //class CTeacher : public CPerson//繼承CPerson類,兩層結構 class CTeacher : public CStudent//繼承CStudent類,三層結構 { char *major; //教師專業 float salary; //教師的工資 public: CTeacher(){cout<<"constructor - CTeacher! "<<endl;} ~CTeacher(){cout<<"deconstructor - CTeacher! "<<endl;} }; //實驗主程序 void main() { //CPerson person; //CStudent student; CTeacher teacher; }