1)为什么要继承
实现代码复用。
在实例化一个派生类对象时,先调用基类构造函数,在调用派生类构造函数;
销毁派生类对象时,析构函数调用顺序正好相反
#include<iostream>
#include<string>
using namespace std;
class Person{
public:
Person(){
cout << "Person()" << endl;
}
~Person(){
cout << "~Person()" << endl;
}
void eat(){
cout << "eat()" << endl;
}
string m_strName;
int m_iAge;
};
class Worker :public Person{
public:
Worker(){
cout << "Worker()" << endl;
}
~Worker(){
cout << "~Worker()" << endl;
}
void worker(){
cout << "worker()" << endl;
}
int m_iSalary;
};
int main(){
Worker *pWorker = new Worker();
delete pWorker;
pWorker = NULL;
return 0;
}
2)继承方式
a.公有继承
class A:public B
基类 public protected private
派生类 public protected 无法访问
b)保护继承
class A:protected B
基类