继承中的对象模型:
在子类对象构造时,需要调用父类的构造函数对其继承得来的成员进行初始化;
在子类对象析构时,需要调用父类的析构函数对其继承得来的成员进行清理;
#include<iostream>
using namespace std;
class Parent
{
public:
void printp()
{
cout << "我是爹" << endl;
}
Parent(char *p)//当父类构造函数有参数时,需要在子类的初始化列表中显示调用。
{
cout << "调用构造函数" << endl;
}
~Parent()
{
cout << "调用析构函数" << endl;
}
protected:
int a;
int b;
private:
};
class Child:public Parent
{
public:
Child():Parent("abcd")//初始化列表
{
a = 0;
b = 0;
c = 0;
cout << "调用子类的构造函数" << endl;
}
~Child()
{
cout << "调用子类的析构函数" << endl;
}
void printp()
{
cout << "我是儿子" << endl;
}
private:
int c;
protected:
};
void printfp(Parent *P)
{
P->printp();
}
int main()
{
Parent p("abcd");
Child c;//先调用父类的构造函数,再调用子类的构造函数。
system("pause");
return 0;
}