[英]I am new in C++, I want to know, why the pure virtual function is used in c++ ?. Why to use pure virtual function?
I am new in C++, I want to know, why the pure virtual function is used in c++?.我是C++的新手,想知道为什么c++使用纯虚拟function? Somewhat I know to make class abstract and force all derived Classes to have implementation.
我知道使 class 抽象并强制所有派生类具有实现。 But I want to know what is the situation where only pure virtual function can work?
但是我想知道只有纯虚拟function可以工作的情况是什么?
Assume you have a certain base class defining a type like GeometricForm
which has a virtual function float calculateArea()
.假设你有一个特定的基础 class 定义了一个像
GeometricForm
这样的类型,它有一个虚拟的 function float calculateArea()
。 You cannot calculate the area for GeometricForm
because GeometricForm
itself does not define a geometric form (hope this is understandable).您无法计算
GeometricForm
的面积,因为GeometricForm
本身并没有定义几何形状(希望这是可以理解的)。 But you can create a derived class eg Circle
of this base class which is an actual geometric form.但是您可以创建一个派生的 class 例如这个基础 class 的
Circle
,这是一个实际的几何形式。
You now want to be sure that this derived class implements a valid version of your former virtual function calculateArea()
, which will be ensured by the compiler.您现在要确保这个派生的 class 实现了您以前的虚拟 function
calculateArea()
的有效版本,编译器将确保这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.