标签:os io div sp amp on c ad c++
通过下面的例子,我们来看一下基类与派生的构造函数的调用顺序。创建时先基类后派生类。销毁时先派生类后基类。

#include<iostream>#include<string>using namespacestd;classCBase { string name;intage;public: CBase() { cout <<"BASE" << endl; } ~CBase() { cout <<"~BASE" << endl; } };classCDerive :publicCBase {public: CDerive() { cout <<"DERIVE" << endl; } ~CDerive() { cout <<"~DERIVE" << endl; } };intmain ( ) { CDerive d;return0; }
当有参数时,参数必须传送给基类。注意例子中传递的方法(第8行、第19行)。

#include<iostream>#include<string>using namespacestd;classCBase { string name;public: CBase(string s) : name(s) { cout <<"BASE: " << name << endl; } ~CBase() { cout <<"~BASE" << endl; } };classCDerive :publicCBase {intage;public: CDerive(string s,inta) : CBase(s), age(a) { cout <<"DERIVE: " << age << endl; } ~CDerive() { cout <<"~DERIVE" << endl; } };intmain ( ) { CDerive d("小雅", 27);return0; }
当有三层继承时,参数要一层一层地传递下去(第30行、第19行、第8行)。

#include<iostream>#include<string>using namespacestd;classCBase { string name;public: CBase(string s) : name(s) { cout <<"BASE: " << name << endl; } ~CBase() { cout <<"~BASE" << endl; } };classCDerive :publicCBase {intage;public: CDerive(string s,inta) : CBase(s), age(a) { cout <<"DERIVE: " << age << endl; } ~CDerive() { cout <<"~DERIVE" << endl; } };classCSon :publicCDerive { string id;public: CSon(string s1,inta, string s2) : CDerive(s1, a), id(s2) { cout <<"SON: " << id << endl; } ~CSon() { cout <<"~SON" << endl; } };intmain ( ) { CSon s("小雅", 27,"8503026");return0; }
标签:os io div sp amp on c ad c++
原文地址:http://www.cnblogs.com/notlate/p/3947146.html