#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;
}
注意:构造函数和析构函数的调用顺序相反