1. 继承的基本语法
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
//继承
//继承的好处:减少重复代码量
//父类
class CAT
{
public:
void leg()
{
cout << "Cats have four legs." << endl;
}
void eye()
{
cout << "Cats have two big eyes." << endl;
}
void voice()
{
cout << "A cat`s voice is meow." << endl;
}
};
//子类
//每个子类都可以继承父类的一些属性
//Orange cat
class OrangeCat: public CAT
{
public:
void special()
{
cout << "The orange cat are usually fat." << endl;
}
};
//milk cat
class MilkCat : public CAT
{
public:
void special()
{
cout << "The milk cat are usually funny." << endl;
}
};
//ragdoll
class Ragdoll : public CAT
{
public:
void special()
{
cout << "The ragdoll are usually elegant." << endl;
}
};
void test01()
{
OrangeCat oo;
oo.eye();
oo.leg();
oo.voice();
oo.special();
cout << "------------------------------------" << endl;
MilkCat mm;
mm.eye();
mm.leg();
mm.voice();
mm.special();
cout << "------------------------------------" << endl;
Ragdoll rr;
rr.eye();
rr.leg();
rr.voice();
rr.special();
cout << "------------------------------------" << endl;
}
int main()
{
test01();
return 0;
}
2. 继承方式
3. 继承中的对象类型
示例:
结果:Son 的大小为16
原因:父类中的所有非静态成员属性都会被子类继承下去。父类的私有属性也会被继承,只是在子类继承之后会被编译器隐藏,因此不能被访问。
在开发人员命令提示符中查看对象模型:
步骤:
4. 继承中的构造和析构函数
先构造父类,再构造子类;
先析构子类,再析构父类。
5. 继承同名成员处理方式
Note:成员函数和成员对象同理
6. 继承同名静态成员成员处理方式
7. 多继承语法
8. 菱形继承
菱形继承存在的问题:
当孙类访问父类中的某一个成员对象时, 由于两个子类都继承了父类,因此继承了子类的孙类中就会存在两份数据。
为了解决这种情况,通过添加关键字 “virtual” (子类继承父类的时候采用虚继承)使孙类中只包含一份数据。