抽象类
抽象类的初衷
- 给出共性属性,让派生类通过继承直接复用这些属性
- 给所有的派生类保留统一的覆盖/重写接口
抽象类
- 拥有纯虚函数
func(para)=0
的类,叫做抽象类 - 抽象类不可以直接实例化对象,但可以定义指针和引用变量
#include <iostream>
using namespace std;
#include <string>
class Car
{
public:
Car(string name, double oil) : _name(name), _oil(oil) {}
double getLeftMiles() {
return _oil * getMilesPerGallon(); //发生动态绑定
}
string getName() { return _name; }
protected:
string _name;
double _oil;
virtual double getMilesPerGallon() = 0; //纯虚函数
};
double showLeftMiles(Car& car)
{
return car.getLeftMiles();
}
class Benz : public Car
{
public:
Benz(string name, double oil) : Car(name, oil) {}
double getMilesPerGallon() { return 19.0; }
};
class BMW : public Car
{
public:
BMW(string name, double oil) : Car(name, oil) {}
double getMilesPerGallon() { return 17.0; }
};
class Audi : public Car
{
public:
Audi(string name, double oil) : Car(name, oil) {}
double getMilesPerGallon() { return 16.0; }
};
int main()
{
Benz c1("Benz", 10.0);
cout << c1.getName() << ": " << showLeftMiles(c1) << endl;
BMW c2("BMW", 10.0);
cout << c2.getName() << ": " << showLeftMiles(c2) << endl;
Audi c3("Audi", 10.0);
cout << c2.getName() << ": " << showLeftMiles(c3) << endl;
return 0;
}
标签:oil,name,33,double,Car,抽象类,public
From: https://www.cnblogs.com/sio2zyh/p/17987575