对象是由“底层向上”开始构造的,当创建一个对象时,首先调用基类的构造函数,而后调用下一个派生类的构造函数,依次类推,直至到达派生类次数最多的派生次数最多的类的构造函数为止。由于,构造函数一开始构造时,老是要调用它的基类的构造函数,而后才开始执行其构造函数体,调用直接基类构造函数时,若是无专门说明,就调用直接基类的默认构造函数。在对象析构时,其顺序正好相反。 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; }