1.什么是继承
当创建对象时,是先调用父类的构造函数还是子类的构造函数呢?
当销毁对象时,是先调用父类的析构函数还是子类的析构函数呢?
下面一段代码揭晓:
/*Person.h*/
#include<string>
using namespace std;
class Person
{
public:
Person();
~Person();
void eat();
string m_strName;
int m_iAge;
};
/*Person.cpp*/
#include<iostream>
#include"Person.h"
using namespace std;
Person::Person()
{
cout << "Person() "<< endl;
}
Person::~Person()
{
cout << "~Person() "<< endl;
}
void Person::eat()
{
cout << "eat() "<< endl;
}
/*Worker.h*/
#include"Person.h"
class Worker:public Person
{
public:
Worker();
~Worker();
void work();
int m_iSalary;
};
/*Worker.cpp*/
#include<iostream>
#include"Worker.h"
using namespace std;
Worker::Worker()
{
cout << "Worker() " << endl;
}
Worker::~Worker()
{
cout << "~Worker() " << endl;
}
void Worker::work()
{
cout << "work() " << endl;
}
/*demo.cpp*/
#include<iostream>
#include<stdlib.h>
#include"Worker.h"
using namespace std;
int main(void)
{
Worker *p=new Worker();
delete p;
p = NULL;
system("pause");
return 0;
}
打印结果:
很显然:在创建对象时是先调用父类的构造函数然后再调用子类的构造函数,而在销毁对象时,是先调用子类的析构函数再调用父类的析构函数。两者过程正好。
2.继承方式
2.1 公有继承(public)
2.2 保护继承(protected)
2.3 私有继承(private)
/******************************************************************************************************/
保护继承和私有继承
要求:1.Person类,数据成员:m_strName,成员函数:构造函数、play()
2.soldier类,数据成员:m_iAge,成员函数:构造函数、work()
3.Infantry步兵类,成员函数:attack()
/*******************************************************************************************************/
代码展示:
/*Person.h*/
#include<string>
using namespace std;
class Person
{
public:
Person();
void play();
protected:
string m_strName;
};
/*Person.cpp*/
#include<iostream>
#include"Person.h"
using namespace std;
Person::Person()
{
m_strName = "Merry";
}
void Person::play()
{
cout << "Person----play() "<< endl;
cout << m_strName << endl;
}
/*士兵类*/
#include"Person.h"
class Soldier:protected Person
{
public:
Soldier();
void work();
protected:
int m_iAge;
private:
};
#include<iostream>
#include"Soldier.h"
using namespace std;
Soldier::Soldier()
{
}
void Soldier::work()
{
m_strName = "Jim";
m_iAge = 20;
cout << m_strName << endl;
cout << m_iAge << endl;
cout << "Soldier---work()" << endl;
}
/*步兵类*/
#include"Soldier.h"
class Infantry:private Soldier
{
public:
void attack();
};
#include<iostream>
#include"Infantry.h"
using namespace std;
void Infantry::attack()
{
m_strName = "Jim";
cout << m_strName << endl;
cout << "Infantry--attack()" << endl;
}
运行结果:
Soldier 保护继承 Person
Infantry 保护继承 Soldier
最后通过Infantry的成员函数访问到了Person的保护成员
3.继承中的特殊关系----隐藏
什么情况下会发生隐藏: 父子关系->函数同名->隐藏
在这种情况下,当调用ABC()这个函数时,其实是调用子类中的函数,而隐藏了父类的同名函数,如果要调用父类的成员函数,就要写成父类名称::ABC()。