标签:
参考1: C++继承中构造函数、析构函数调用顺序及虚函数的动态绑定
参考2: 构造函数、拷贝构造函数和析构函数的的调用时刻及调用顺序
参考3: C++构造函数与析构函数的调用顺序
拷贝构造函数实际上也是构造函数,具有一般构造函数的所有特性,其名字也与所属类名相同。拷贝构造函数中只有一个参数,这个参数是对某个同类对象的引用。它在三种情况下被调用:
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 }
标签:
原文地址:http://www.cnblogs.com/guxuanqing/p/5866760.html