纯虚函数:没有函数体且初始化为0的虚函数,用来定义函数规范
抽象类:含有纯虚函数的类,不可以实例化对象(创建对象)
抽象类也可以包含非纯虚函数,成员变量
如果父类是抽象类,子类没有完全实现纯虚函数,那么这个子类依旧是抽象类。
#include
using namespace std;
class person
{
int age;
int height;
public:
person(int m_age = 22, int m_height = 22) : age(m_age), height(m_height) {}
virtual void print_age() = 0;
virtual void print_height() = 0; //将基类定义成纯虚函数
int age_print()
{
return age;
}
int height_print()
{
return height;
}
};
class father : public person //虚基类
{
public:
father(int ff_age, int ff_height) : person(ff_age, ff_height){};
void print_height()
{
cout << "father-height " << height_print() << endl;
}
};
class son : public father
{
public:
son(int ss_age, int ss_height) : father(ss_age, ss_height){}; //跳过中间类father,直接使用基类构造函数,只适合虚基类
void print_age()
{
cout << "son-age " << age_print() << endl;
}
};
int main()
{
// person p; //报错 纯虚函数是抽象类,不能定义对象
// father p; //报错,子类不完全重写父类person 纯虚函数,子类也是抽象类
son p(23, 44);//son 本身重写了父类的print_age() 又继承了father重写父类的print_height() ,所以子类是完全重写可以定义对象
p.print_age();
p.print_height();
}