0、用到的类的声明定义:
human.h,huamn.cpp,man.h,man.cpp,woman.h,woman.cpp
类在:
C++基础知识,C++11中的多态和重载,函数遮蔽,using多态的引入
其他类:
abstractFather.h
#ifndef __ABSTRACTFATHER__
#define __ABSTRACTFATHER__
class abstractFather
{
public:
abstractFather();
virtual ~abstractFather();
virtual void eat() = 0;
};
#endif // !
abstractFather.cpp
#include "abstractFather.h"
#include<iostream>
abstractFather::abstractFather()
{
std::cout << "abstractFather::abstractFather()" << std::endl;
}
abstractFather::~abstractFather()
{
std::cout << "abstractFather::~abstractFather()" << std::endl;
}
son.h
#ifndef __SON__
#define __SON__
#include"abstractFather.h"
class son :public abstractFather
{
public:
son();
~son();
virtual void eat();
};
#endif // !son
son.cpp
#include "son.h"
#include<iostream>
son::son()
{
std::cout << "son::son()" << std::endl;
}
son::~son()
{
std::cout << "son::~son()" << std::endl;
}
void son::eat()
{
std::cout << "void son::eat()" << std::endl;
}
1、基类指针,子类指针
基类/父类指针可以new一个子类对象
但是不能使用子类的成员函数,那么这样有什么用处呢?
2、虚函数
这样就可以声明一个基类的指针,调用父类的函数,覆盖,再调用任意子类的函数
Huamn* human = new Man;
human->eat();
delete human;
human = new Huamn;
human->eat();
delete human;
human = new Woman;
human->eat();
delete human;
在子类中,virtual可加可不加,上最好也加上virtual,别人看代码时比较友好
- override,为了避免在子类中写错虚函数,就要在子类声明中,虚函数的末尾加上override编译器回去找父类中的同名虚函数,如果写错了,编译器会纠错
- final也是虚函数专用,但是在基类中的virtual函数末尾加上final,子类就不能重写override
- 调用虚函数是动态执行的,只有在程序运行的时候才知道,必须要写定义部分(内容)
3、纯虚函数
在virtual函数末尾加上 = 0,
一旦一个类中有了纯虚函数,就不能实例化了,这个类就叫做抽象类了。
- 1、抽象类不能用来生成对象,主要用来管理子类对象
- 2、子类必须实现纯虚函数
4、基类的析构函数,一定要是虚函数
因为 父类指针指向new 子类时
,delete不会调用子类的析构函数
,但是如果基类中析构声明成了虚函数
,
则会默认调用子类析构函数
虚函数会增加内存开销,给类增加虚函数表,虚函数指针
abstractFather* pf = new son;
delete pf;
执行结果