在 C++ 中使用抽象类实现接口
在 Java 中,多重继承是使用 interface
实现的。interface
就像一个模板,因为它包含必要的布局,但它是抽象的或没有方法体。
对于 C++,不需要接口,因为 C++ 支持多重继承,这与 Java 不同。在 C++ 中,接口的功能可以使用抽象类来实现。
C++ 中抽象类的概念
抽象类是具有至少一个纯虚函数的类。只能声明一个纯虚函数,它不能有定义,它是通过在声明中赋值 0
来声明的。
抽象类对于使代码可重用和可扩展非常有用。这是因为可以创建许多从父类继承但具有唯一定义的派生类。
此外,抽象类不能被实例化。
例子:
class A {
public:
virtual void b() = 0; //function "b" in class "A" is an example of a pure virtual function
};
在函数声明期间,试图在定义函数时使其成为纯虚拟函数是行不通的。
使用 C++ 在程序中实现纯虚函数
考虑一个以 shape
作为父类的示例。当涉及到形状时,它们有许多不同的类型,当我们需要计算属性时,例如面积,我们计算它的方式因形状而异。
rectangle
和 triangle
作为从 shape
的父类继承的派生类。然后,我们将在它们自己的派生类中为每个形状(矩形
和三角形
)提供具有所需定义的纯虚函数。
源代码:
#include <iostream>
using namespace std;
class Shape {
protected:
int length;
int height;
public:
virtual int Area() = 0;
void getLength() {
cin >> length;
}
void getHeight() {
cin >> height;
}
};
class Rectangle: public Shape {
public:
int Area() {
return (length*height);
}
};
class Triangle: public Shape {
public:
int Area() {
return (length*height)/2;
}
};
int main() {
Rectangle rectangle;
Triangle triangle;
cout << "Enter the length of the rectangle: ";
rectangle.getLength();
cout << "Enter the height of the rectangle: ";
rectangle.getHeight();
cout << "Area of the rectangle: " << rectangle.Area() << endl;
cout << "Enter the length of the triangle: ";
triangle.getLength();
cout << "Enter the height of the triangle: ";
triangle.getHeight();
cout << "Area of the triangle: " << triangle.Area() << endl;
return 0;
}
输出:
Enter the length of the rectangle: 2
Enter the height of the rectangle: 4
Area of the rectangle: 8
Enter the length of the triangle: 4
Enter the height of the triangle: 6
Area of the triangle: 12
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.