在继承与派生的关系中,派生类会继承基类全部函数,但是不包括构造和析构函数。
解决这个问题的思路是在派生类的构造函数中调用基类构造函数,由基类的构造函数负责完全对基类成员变量的初始化工作。
(1)构造函数调用顺序
1.先调用基类构造函数
2.再调用子对象构造函数
3.最后调用派生类构造函数
(2)析构函数调用顺序:
1.先调用派生类构造函数
2.再调用子对象构造函数
3.最后调用基类构造函数
#include<iostream>
#include<string>
using namespace std;
class Time
{
public:
Time(int y,int mo,int d)
{
year=y;
month=mo;
day=d;
cout<<"子对象time构造函数被调用!"<<endl;
}
~Time()
{
cout<<"子对象time析构函数被调用!"<<endl;
}
void ShowTime()
{
cout<<"year:"<<year<<endl;
cout<<"month:"<<month<<endl;
cout<<"day:"<<day<<endl;
}
private:
int year;
int month;
int day;
};
class Clock
{
public:
Clock(int h,int m,int s);
void ShowClock()
{
cout<<"hour:"<<hour<<endl;
cout<<"minute:"<<minute<<endl;
cout<<"second:"<<second<<endl;
}
~Clock()
{
cout<<"基类Clock析构函数被调用!"<<endl;
}
protected:
int hour;
int minute;
int second;
};
class Date:public Clock
{
public:
Date(int h,int m,int s,string w,int y,int mo,int d):time(y,mo,d), Clock(h,m,s)
{
week=w;
cout<<"派生类Date构造函数被调用!"<<endl;
}
~Date()
{
cout<<"派生类Date析构函数被调用!"<<endl;
}
void ShowDate()
{
time.ShowTime();
cout<<"week:"<<week<<endl;
ShowClock();
}
private:
string week;
Time time;
};
Clock::Clock(int h,int m,int s)
{
hour=h;
minute=m;
second=s;
cout<<"基类Clock构造函数被调用!"<<endl;
}
int main()
{
Date d(15,5,30,"星期六",2022,5,14);
d.ShowDate();
return 0;
}