问题描述
纯虚函数和虚函数之间?
What is the difference between a pure virtual function and a virtual function?
我知道纯虚函数是一个没有主体的虚函数,但是这意味着什么,实际上是由下面的行做的:
I know "Pure Virtual Function is a Virtual function with no body", but what does this mean and what is actually done by the line below:
virtual void virtualfunctioname() = 0
推荐答案
一个虚函数使其类成为一个多态基类。派生类可以覆盖虚函数。通过基类指针/引用调用的虚函数将在运行时解析。也就是说,使用对象的动态类型代替其静态类型
A virtual function makes its class a polymorphic base class. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the dynamic type of the object is used instead of its static type:
Derived d;
Base& rb = d;
// if Base::f() is virtual and Derived overrides it, Derived::f() will be called
rb.f();
纯虚函数是一个虚函数,声明以 = 0
:
A pure virtual function is a virtual function whose declaration ends in =0
:
class Base {
// ...
virtual void f() = 0;
// ...
一个纯虚函数隐式地使它被定义为 abstract (与在Java中你有一个关键字来显式地声明类abstract)不同。抽象类不能实例化。派生类需要重写/实现所有继承的纯虚函数。如果他们没有,它们也会变得抽象。
A pure virtual function implicitly makes the class it is defined for abstract (unlike in Java where you have a keyword to explicitly declare the class abstract). Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract.
C ++的一个有趣的特性是,一个类可以定义一个具有实现的纯虚函数。
(。)
An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation.(What that's good for is debatable.)
注意,C ++ 11为 delete
和默认
关键字看起来类似于纯虚函数的语法:
Note that C++11 brought a new use for the delete
and default
keywords which looks similar to the syntax of pure virtual functions:
my_class(my_class const &) = delete;
my_class& operator=(const my_class&) = default;
请参阅和了解有关使用 delete
的更多信息和默认
。
See this question and this one for more info on this use of delete
and default
.
这篇关于虚函数和纯虚函数之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!