纯虚函数:
- 是虚函数的一种,无函数体,函数 = 0
形如: virtual void print() = 0;
抽象类:
- 至少包含一个纯虚函数
- 抽象类不能实例化,(但可以用指针,这是C++多态的体现)
多态
多态:同一种行为的不同结果
必要性原则:
- 必须是公有继承
- 必须存在virtual类型
多态的列子:
class Father {
public:
virtual void print()
{
cout << "父类的Father::print" << endl;
}
protected:
};
class Son :public Father
{
public:
void print()
{
cout << "子类的Son::print"<
//正常调用: 父类指针指向父类对象
Father* pFather = new Father;
pFather->print(); //调用父类的print
Son* pSon = new Son;
pSon->print(); //调用子类的print(子类覆盖父类方法)
//父类指针指向子类对象
pFather = new Son;
pFather->print(); //调用子类的print
//(无virtual看指针类型 有virtual看对象类型
pFather = new Father;
pFather->print(); //调用父类的print 这是多态
system("pause");
return 0;
}
结果:
父类的Father::print 子类的Son::print 子类的Son::print 父类的Father::print



