抽象函数指的是没有具体内容的函数,一般用"= 0"修饰,例如:
class A{
public:
virtual void func() = 0;
};
上面的虚函数func即为一个抽象函数。所谓的抽象类即指含有至少一个抽象函数的类。抽象类不能被实例化,抽象函数一旦被实例化,则会产生报错 “can not declare variable xx to be abstract type xx”。那么抽象类到底有何用呢?抽象类实际上是提供了一个接口,以便于用户在使用的时候可以不必关心功能是如何实现的,只需要关心有什么功能。例如大家都知道一辆汽车有转向灯,有油门踏板,有刹车,有方向盘。司机只需知道,踏下踏板,汽车就会加速,转向时只需扳动一下,对应的转向灯就会亮起。至于这些功能是如何实现的,司机完全不必关心,这是汽车制造商的任务。同样的抽象类就是把所有的可用的函数暴露出来给用户,至于内部怎么实现的则全部被隐藏在其他的类或文件中,用户完全不必关心实现方法。例如以下模拟汽车行驶的程序中:
#include <iostream>
#include <ctime>
using namespace std;
class Car{
public:
virtual void accelerate() = 0; //定义汽车里的加速函数
virtual void decelerate() = 0; //定义汽车里的减速函数
virtual double showDistance() = 0; //显示行驶路程
virtual double showSpeed()const = 0; //显示速度
virtual double showTank()const = 0; //显示油量
};
class CarImplement : public Car{
private:
double _Distance;
double _Speed;
double _Tank; //在执行类中定义记录数据的属性
public:
CarImplement(int dis, int speed, double tank){
this->_Distance = dis;
this->_Speed = speed;
this->_Tank = tank;
}
void accelerate(){
this->_Speed += 5; //每调用一次加速函数,速度提升5km/h
this->_Tank -= 0.1; //每调用一次加速函数,耗油0.05L
}
void caculateDistance(){
this->_Distance += this->_Speed * 0.2; //每3秒记录一次速度,同时油量降低0.1L
if(this->_Speed != 0) //如果速度为0,则油量不会减少
this->_Tank -= 0.2;
}
void decelerate(){
this->_Speed -= 5; //每调用一次减速函数,速度降低5km/h
}
double showDistance(){
this->caculateDistance(); //显示距离之前先计算一下距离
return this->_Distance;
}
double showTank()const{ //显示油量
return this->_Tank;
}
double showSpeed()const{ //显示速度
return this->_Speed;
}
};
int main(){
srand(time(0));
Car* car = new CarImplement(0, 0, 6.0); //使用抽象类指针实例化一辆汽车
cout << "Current travel distance\t\t" << "Current speed\t\t" << "Remaining oil" << endl << endl;
for(;;){
cout << car->showDistance() << "\t\t\t\t";
cout << car->showSpeed() << "\t\t\t";
cout << car->showTank() << "\t" << endl << endl;
if(rand() % 2 == 0)
car->accelerate();
if(rand() % 5 == 0 && car->showSpeed() > 5) //用随机数模拟加速和遇到障碍需要减速情况
car->decelerate();
if(car->showTank() < 0.3){
cout << "oil was out of" << endl;
break;
} //当油耗尽时即停止
}
}
用户只需要调用加速减速函数即可控制汽车的行驶,而不必关心加速减速如何做到的。抽象类我们又称之为接口(interface),接口类中允许存在一个析构函数,但不允许存在构造函数。
如有错误,欢迎批评与指正!