为什么我们需要C ++中的接口或纯虚函数 [英] why we need interface or pure virtual function in c++

查看:49
本文介绍了为什么我们需要C ++中的接口或纯虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们需要c ++中的接口(纯虚函数或抽象类)?我们可以拥有一个定义了虚函数的基类,而不是抽象类,并在派生类中重写该虚函数.上面的方法(除了我们可以创建基类的对象之外)的优点和缺点是什么?

why we need interface ( pure virtual function or abstract class) in c++? Instead of having abstract class, Can we have a base class with virtual function defined in it, and override that virtual function in derived class. what would be the advantage and disadvantage with the above approach ( except we can create the object of the base class)?

推荐答案

纯虚函数适用于在基类中没有明智的方式实现该函数的情况.例如:

Pure virtual functions are for when there's no sensible way to implement the function in the base class. For example:

class Shape {
public:
    virtual float area() const = 0;
};

您可以编写派生类,例如 Circle Rectangle ,这些类使用用于这些形状的特定公式来实现 area().但是,如果它不是纯虚拟的,您将如何在 Shape 本身中实现 area()?您如何在不知道形状是什么的情况下计算形状的面积?

You can write derived classes like Circle and Rectangle that implement area() using the specific formulas for those kinds of shapes. But how would you implement area() in Shape itself, if it weren't pure virtual? How do you compute the area of a shape without even knowing what kind of shape it is?

如果您的函数 可以在基类中实现(以一种有用的方式),则继续进行实现.并非所有的基类都必须是抽象的.但是其中有些只是天生的 ,例如 Shape .

If your function can be implemented (in a useful way) in the base class, then go ahead and implement it. Not all base classes need to be abstract. But some of them just inherently are abstract, like Shape.

这篇关于为什么我们需要C ++中的接口或纯虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆