虚函数

  • 虚函数是在基类中声明的成员函数,前面加上virtual关键字
  • 允许在派生类中重写这个函数,并且可以通过基类指针或者引用调用时,自动选择正确的函数版本
    如果在派生类中不打算重写基类的虚函数,可以在声明时使用final防止重写
    用处:
    需要通过继承来扩展功能并保持代码的可维护性和灵活性

纯虚函数

  • 是一种特殊的虚函数
  • 在基类中声明,但是没有实现
  • 纯虚函数使用=0来声明,表示该函数必须在派生类中被重写

抽象类:

  • 包含纯虚函数的类叫做抽象类
  • 抽象类不能实例化对象,只能作为其他类的基类
    举例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    //定义抽象类Base
    class Base{
    public:
    vitrual int doSomething() = 0;//纯虚函数,为抽象类
    };
    class Derived: public Base{
    public:
    int doSomething()override{/*具体实现*/return 0;}
    };
    int main(){
    Base* pbase = new Base();//错误
    Base* pderived = new Derived();//正确
    }

举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Shape {
public:
virtual double area() const = 0; // 纯虚函数
};

class Circle : public Shape {
public:
double radius;
Circle(double r) : radius(r) {}
double area() const override { return 3.14 * radius * radius; }
};

class Rectangle : public Shape {
public:
double width, height;
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override { return width * height; }
};

int main() {
Shape* shapes[] = {new Circle(5), new Rectangle(4, 6)};
for (auto shape : shapes) {
std::cout << "Area: " << shape->area() << std::endl;
}
for (auto shape : shapes) {
delete shape; // 释放内存
}
return 0;
}