一、什么是抽象类
至少拥有一个纯虚函数的类叫做抽象类。那什么是纯虚函数呢?纯虚函数是指用virtual关键字修饰的,在具体实例化时候才实现具体内容的函数,编写方式如下:
virtual void V_Fun() = 0;
当开头用virtual关键字修饰,并且在结尾赋值为0的函数,我们就可以称之为纯虚函数。
二、抽象类注意事项
1. 抽象类只能用作其他类的基类
2. 不能使用抽象类定义对象
3. 抽象类可以拥有构造方法和析构方法
4. 抽象类不可以作为参数类型,返回值类型或显示转换类型
三、小例子(动物:猫、狗)
以下是一个关于抽象类的小例子,以便具体的理解,Animal类便是一个拥有两个纯虚函数的抽象类,而Dog和Cat是继承Animal类的两个子类。
#include <iostream>
#include <string>using namespace std;class Animal {protected : string type;string sound;public :Animal(string type, string sound) {this->sound = sound;this->type = type;}virtual void yell(int degree) = 0;virtual string action() = 0;
}; class Dog : public Animal {public :Dog(string type, string sound) : Animal(type, sound) {}virtual void yell(int degree) {cout << this->type << " : ";for(int i = 0; i < degree; i++) {cout << this->sound << " "; }cout << endl;}virtual string action() {return "啃了啃骨头";}
};class Cat : public Animal {public :Cat(string type, string sound) : Animal(type, sound) {}virtual void yell(int degree) {cout << this->type << " : ";for(int i = 0; i < degree; i++) {cout << this->sound << " "; }cout << endl;}virtual string action() {return "玩了玩毛线球";}
};int main() {Dog dog("小狗", "汪汪");Cat cat("小猫", "喵喵");cout << "小狗动作:" << dog.action() << endl;dog.yell(2);cout << "小猫动作:" << cat.action() << endl;cat.yell(5);return 0;
}