问题描述
我刚刚在我的 OOP 类中了解了多态性,但我很难理解抽象基类的用途.
I've just learned about polymorphism in my OOP Class and I'm having a hard time understanding how abstract base classes are useful.
抽象类的目的是什么?定义一个抽象基类提供了什么,而不是通过在每个实际类中创建每个必要的函数来提供?
What is the purpose of an abstract class? What does defining an abstract base class provide that isn't provided by creating each necessary function in each actual class?
推荐答案
抽象类的目的是为一组具体的子类定义一个通用协议.这在定义共享代码、抽象想法等的对象时很有用.
The purpose of an abstract class is to define a common protocol for a set of concrete subclasses. This is useful when defining objects that share code, abstract ideas, etc.
抽象类没有实例.一个抽象类必须至少有一个延迟的方法(或函数).为了在 C++ 中实现这一点,在抽象类中声明了一个纯虚成员函数,但没有定义:
Abstract classes have no instances. An abstract class must have at least one deferred method (or function). To accomplish this in C++, a pure virtual member function is declared but not defined in the abstract class:
class MyClass {
virtual void pureVirtualFunction() = 0;
}
尝试实例化抽象类总是会导致编译器错误.
Attempts to instantiate an abstract class will always result in a compiler error.
"定义抽象基类提供了哪些未提供的通过在每个实际类中创建每个必要的函数?"
这里的主要思想是代码重用和跨类的适当分区.在父类中定义一次函数比在多个子类中一遍又一遍地定义更有意义:
The main idea here is code reuse and proper partitioning across classes. It makes more sense to define a function once in a parent class rather than defining over and over again in multiple subclasses:
class A {
void func1();
virtual void func2() = 0;
}
class B : public A {
// inherits A's func1()
virtual void func2(); // Function defined in implementation file
}
class C : public A {
// inherits A's func1()
virtual void func2(); // Function defined in implementation file
}
这篇关于为什么我们需要 C++ 中的抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!