什么是纯虚函数?
纯虚函数是将基类中的函数声明为虚函数=0的函数。纯虚函数只能声明,不能定义,因为纯虚函数没有函数体。纯虚函数的写法为 virtual 函数返回类型 函数名(参数列表)=0; 其中 =0 并不是将函数赋值为0,而是告知编译器这是纯虚函数。
什么是抽象类
包含纯虚函数的类称为抽象类,一般都是将基类写成抽象类,由于纯虚函数没有函数体,因此无法定义,不能被调用,系统也就无法为其分配内存,所以抽象类不能实例化对象。基类中的纯虚函数可以由派生类去实现,但是需要派生类将基类中的纯虚函数全部实现,否则派生类将无法实例化。(假如基类中有两个纯虚函数,派生类只实现了一个,那么将无法实例化)
#include <iostream>
#include <thread>
using namespace std;
class People {
public:
People(int b);
virtual ~People();
virtual void run() = 0;
virtual int swim(int a) = 0;
private:
int b;
};
People::People(int b) : b(b) { cout << "People constructed is created" << endl; }
People::~People() { cout << "People destructed is used" << endl; }
class SonPeople : public People {
public:
SonPeople(int b, int c);
~SonPeople();
int swim(int a);
void run();
private:
int c;
};
SonPeople::SonPeople(int b, int c) : People(b), c(c) {
cout << "SonPeople constructed is created" << endl;
}
SonPeople::~SonPeople() { cout << "SonPeople destructed is used" << endl; }
int SonPeople::swim(int a) { return 0; }
void SonPeople::run() { cout << "this is run function" << endl; }
int main() {
People *ptr = new SonPeople(2, 3);
int swim = ptr->swim(3);
cout << "ptr->swim():" << swim << endl;
ptr->run();
delete ptr;
return 0;
}
输出:
People constructed is created
SonPeople constructed is created
ptr->swim():0
this is run function
SonPeople destructed is used
People destructed is used
在实际开发中,你可以定义一个抽象基类,只完成部分功能,未完成的功能交给派生类去实现(谁派生谁实现)。这部分未完成的功能,往往是基类不需要的,或者在基类中无法实现的。虽然抽象基类没有完成,但是却强制要求派生类完成,这就是抽象基类的“霸王条款”。 抽象基类除了约束派生类的功能,还可以实现多态。上述程序中基类指针 ptr 的类型是People,但是它却可以访问派生类中的 swim() 和 run() 函数,这是由于在 People 类中将这两个函数定义为纯虚函数,实现了多态。这或许才是C++提供纯虚函数的主要目的。 关于纯虚函数的几点说明 1.一个纯虚函数就可以使类成为抽象基类,但是抽象基类中除了包含纯虚函数外,还可以包含其它的成员函数(虚函数或普通函数)和成员变量。 2.只有类中的虚函数才能被声明为纯虚函数,普通成员函数和顶层函数均不能声明为纯虚函数
|