在我们学习纯虚函数之前,请务必查看这些教程
C++ Pure Virtual Functions
纯虚函数用于
- 如果函数在基类中没有使用
- 但所有派生类都必须实现该函数
我们来看一个例子,
假设我们从 Shape
类派生了 Triangle
、Square
和 Circle
类,并且我们想计算所有这些形状的面积。
在这种情况下,我们可以在 Shape
中创建一个名为 calculateArea()
的纯虚函数。由于它是纯虚函数,所有派生类 Triangle
、Square
和 Circle
都必须包含带实现的 calculateArea()
函数。
纯虚函数没有函数体,必须以 = 0
结尾。例如,
class Shape {
public:
// creating a pure virtual function
virtual void calculateArea() = 0;
};
注意: = 0
语法并不意味着我们将 0 分配给函数。这只是我们定义纯虚函数的方式。
Abstract Class
包含纯虚函数的类称为抽象类。在上面的示例中,Shape
类是抽象类。
我们不能创建抽象类的对象。但是,我们可以从它们派生类,并使用它们的数据成员和成员函数(纯虚函数除外)。
Example: C++ Abstract Class and Pure Virtual Function
// C++ program to calculate the area of a square and a circle
#include <iostream>
using namespace std;
// Abstract class
class Shape {
protected:
float dimension;
public:
void getDimension() {
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0;
};
// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};
int main() {
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;
}
输出
Enter the length of the square: 4 Area of square: 16 Enter radius of the circle: 5 Area of circle: 78.5
在此程序中,Shape
类中的 virtual float calculateArea() = 0;
是一个纯虚函数。
因此,我们必须在我们两个派生类中都提供 calculateArea()
的实现,否则我们会收到错误。