[c++]派生類的構造函數和析構函數

#include<iostream>
using namespace std;
class Base
{
    float x;
    float y;
public:
    Base(float a,float b)
    {
        x = a;
        y = b;
        cout<<"基類構造函數被調用"<<endl;
    }
    ~Base()
    {
        cout<<"基類析構函數被調用"<<endl;
    }
    void print()
    {
        cout<<"x = "<<x<<endl;
        cout<<"y = "<<y<<endl;
    }
};
class Derived:public Base
{
    float z;
    float q;
public:
    Derived(float a,float b,float c,float d):Base(a,b)//以默認參數列表的形式把基類的私有成員賦初值
    {
        z = c;
        q = d;
        cout<<"子類構造函數被調用"<<endl;
    }
    ~Derived()
    {cout<<"子類析構函數被調用"<<endl;}
    void print()
    {
        Base::print();//調用基類的普通重名函數要加作用域哦(同名覆蓋)
        cout<<"z = "<<z<<endl;
        cout<<"q = "<<q<<endl;
    }
};
int main()
{
    Derived b1(11.2,22.3,44.5,6.5);
    b1.print();
    return 0;
}


注意:構造函數和析構函數的調用順序相反

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章