代码改变世界

c++ 基类与派生类的构造函数

2012-06-23 00:01  youxin  阅读(362)  评论(0编辑  收藏  举报

  基类与派生的构造函数的调用顺序。创建时先基类后派生类。销毁时先派生类后基类。

 当有参数时,参数必须传送给基类。注意例子中传递的方法。

#include <iostream>
#include <string>
using namespace std;

class CBase {
    string name;
public:
    CBase(string s) : name(s) {
        cout << "BASE: " << name << endl;
    }
    ~CBase() {
        cout << "~BASE" << endl;
    }
};

class CDerive : public CBase {
    int age;
public:
    CDerive(string s, int a) : CBase(s), age(a) { 
        cout << "DERIVE: " << age << endl;
    }
    ~CDerive() { 
        cout << "~DERIVE" << endl;
    }
};

int main ( ) 
{
    CDerive d("小雅", 27);

    return 0;
}

输出;

BASE: 小雅
DERIVE: 27
~DERIVE
~BASE
请按任意键继续. . .

深入:

http://www.cnblogs.com/kekec/archive/2010/11/16/1878783.html

http://ticktick.blog.51cto.com/823160/294573

http://www.cnblogs.com/xkfz007/archive/2012/05/11/2496447.html

http://topic.csdn.net/t/20060323/14/4634776.html

http://see.xidian.edu.cn/cpp/biancheng/view/232.html

 

http://www.quanxue.cn/JC_CLanguage/Cpp/Cpp08.html