/*
说明: C++继承特性的一些测试
1. 构造函数的调用,发生在创建时,而不是声明时
2. 使用继承,有必要将基类析构函数定义为虚函数(否则将只调用所声明类(一般是基类)的析构函数,这样是不安全的)
3. 若基类某成员方法或析构函数被定义为虚函数,则其派生类相应的成员方法自动变为虚函数(即声明为可以被覆写),此时
派生类中virtual关键字可以加也可以不加(若需要告诉下级派生类,该方法可以被覆盖,往往显式加virtual关键字)。
4. 派生类对基类公有继承,则只能在本派生类内部访问基类protected类型成员(但派生类本质上拥有基类private成员,只是没有访问权)
对public类型成员则无限制
5. 程序效果可以通过分别注释PerSon类中带和不带virtual关键字的析构函数,运行看结果
*/
#include <iostream>
using namespace std;
class Person
{
protected:
int m_identity;
public:
virtual void TellIdentity() = 0;
public:
Person();
virtual ~Person(); //基类析构函数用virtual关键字修饰
//~Person(); //基类析构函数不用virtual关键字修饰
};
class Student :public Person
{
public:
void TellIdentity();
public:
Student();
~Student();
};
class ColledgeStudent :public Student
{
private:
int m_iCET4Score;
public:
void TellIdentity();
public:
ColledgeStudent();
~ColledgeStudent();
};
Person::Person()
{
m_identity = 100;
cout << "PersonClass Constructed." << endl;
}
Person::~Person()
{
cout << "PersonClass Distructed." << endl;
}
Student::Student()
{
cout << "StudentClass Constructed." << endl;
}
Student::~Student()
{
cout << "StudentClass Distructed." << endl;
}
void Student::TellIdentity()
{
cout << "StudentNum is " << m_identity << endl;
}
ColledgeStudent::ColledgeStudent()
{
m_iCET4Score = 460;
cout << "ColledgeStudentClass Constructed." << endl;
}
ColledgeStudent::~ColledgeStudent()
{
cout << "ColledgeStudentClass Distructed." << endl;
}
void ColledgeStudent::TellIdentity()
{
cout << "StudentNum is " << m_identity << endl;
cout << "CET4Score is " << m_iCET4Score << endl;
}
int main()
{
Person *pPer;
pPer = new Student;
pPer->TellIdentity();
delete pPer;
cout << "------------------分割线-----------------" << endl;
pPer = new ColledgeStudent();
pPer->TellIdentity();
delete pPer;
pPer = 0;
return 0;
}