#include <iostream>
using namespace std;
class Parent
{
public:
int m_nAge = 30;
Parent()
{
cout << "The constructor of the parent class "<< endl;
}
virtual void operate()
{
cout << "The operations of the parent class" << endl;
}
virtual ~Parent()
{
cout << "The destructor of the parent class" << endl;
}
};
class Child:public Parent
{
public:
int m_nAge = 10;
Child()
{
cout << "The constructor of the subclass" << endl;
}
void operate()
{
cout << "The operations of the subclass" << endl;
}
~Child()
{
cout << "The destructor of a subclass" << endl;
}
};
int main()
{
Parent *oper = new Child();
oper->operate();
cout << oper->m_nAge << endl;
delete oper;
return 0;
}
执行结果:
不使用多态:
#include <iostream>
using namespace std;
class Parent
{
public:
int m_nAge = 30;
char *m_str;
Parent()
{
m_str = new char[10];
cout << "The constructor of the parent class "<< endl;
}
virtual void operate()
{
cout << "The operations of the parent class" << endl;
}
~Parent()
{
delete []m_str;
cout << "The destructor of the parent class" << endl;
}
};
class Child:public Parent
{
public:
int m_nAge = 10;
char *m_strSub;
Child()
{
m_strSub = new char[10];
cout << "The constructor of the subclass" << endl;
}
void operate()
{
cout << "The operations of the subclass" << endl;
}
~Child()
{
delete []m_strSub;
cout << "The destructor of a subclass" << endl;
}
};
int main()
{
Child *oper = new Child();
oper->operate();
cout << oper->m_nAge << endl;
delete oper;
return 0;
}