问题描述
我刚刚了解了我的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.
一个抽象类?
推荐答案
定义一个抽象基类所提供的定义不是通过在每个实际类中创建每个必要的函数来提供的的抽象类是为一组具体子类定义一个公共协议。这在定义共享代码,抽象概念等的对象时很有用。
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;
}
尝试实例化抽象类将总是导致编译错误。 p>
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 ++中的抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!