接口与抽象类或一般的多态性

用户名

我在理解接口和抽象类的使用之间的区别时遇到了问题。

例如,请参见以下UML图表:

接口与抽象类

两者有什么区别?

马克·A

我将提供代码说明和简短说明。如果您不想阅读,请跳到下面的“简单的英语说明”。


代码说明

  • 用C ++术语来说,抽象类是一个实现一些方法但不实现其他方法的类这意味着:您可以使用它们的某些方法,但是必须实现未实现的方法。

  • 接口是C ++中的纯类,也就是说,一个类不执行任何操作,并且如果您希望您的类与该接口保持一致,则必须执行所有操作

例如-使用下面的链接尝试一下

#include <iostream>
using namespace std;

// Shape is abstract class: some methods are already available, some are not
class Shape
{
public:
  // This is already implemented and ready for polymorphism
  virtual void area() { cout<<"Shape area"<<endl;}
  // You MUST implement this
  virtual void implement_me() = 0;
};

class Circle : public Shape
{
public:
  virtual void area() { cout<<"Circle area"<<endl;}
  void implement_me() { cout<<"I implemented it just because I had to"<<endl;}
};

class HalfCircle : public Circle
{
public:
  virtual void area() { cout<<"HalfCircle area"<<endl;}
};


// ShapeInterface is a pure class or interface: everything must be implemented!
class ShapeInterface
{
public:
  virtual void area() = 0;
};

class CircleFromInterface : public ShapeInterface
{
public:
  // You MUST implement this!
  virtual void area() { cout<<"CircleFromInterface area from interface"<<endl;};
};



int main() {

    Shape* ptr_to_base = new HalfCircle();
    ptr_to_base->area(); // HalfCircle area, polymorphism
    ptr_to_base->Shape::area(); // Shape area
    ptr_to_base->implement_me(); // from Circle


    ShapeInterface *ptr_to_base_int = new CircleFromInterface();
    ptr_to_base_int->area(); // Just the derived has it

    return 0;
}

http://ideone.com/VJKuZx


英文解释

如果您想要过度简化的版本:

  • 接口通常是“合同”,你需要坚持全盘:你需要的一切同意和执行一切,或不工作。

  • 抽象类是部分合同,您必须同意/执行某些事情,但是还有些其他东西已经存在,您可以选择是重新实现(重写)还是懒惰并使用现有的东西。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章