多态性和继承之间有什么区别 [英] what is the difference between polymorphism and inheritance

查看:151
本文介绍了多态性和继承之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对继承和多态性的概念感到困惑。我的意思是,代码重用性和函数覆盖有什么区别?是不可能重用父类函数使用继承概念或否则是不可能重写父类变量使用多态性。对我来说似乎没有什么区别。

I am confused about the concepts of inheritance and polymorphism. I mean, what is the difference between code re-usability and function overriding? Is it impossible to reuse parent class function using inheritance concept or else is it impossible to override parent class variables using Polymorphism. There seems little difference for me.

 class A
{
  public:
      int a;
      virtual void get()
      {
        cout<<"welcome";
      }
};

class B:public A
{
  a =a+1; //why it is called code reuse
  void get() //why it is called overriding
 {
    cout<<"hi";
 }
};

我的疑问是代码重用和函数覆盖之间的区别。

My doubt is about the difference between the code reuse and function overriding.

推荐答案

让我们从你的例子开始。

Lets start with your example.

class A
{
  public:
      int a;
      virtual void get()
      {
        cout<<"welcome";
      }
};

class B:public A
{
  a =a+1; //why it is called code reuse
  void get() //why it is called overriding
 {
    cout<<"hi";
 }
};

继承:在这里你从类A派生类B,这意味着你可以访问它的所有公共变量和方法。

Inheritance: Here you are deriving class B from class A, this means that you can access all of its public variables and method.

a = a + 1

这里您使用 A类的变量 a 正在重复使用中的变量 a ,从而实现代码的可重用性。

Here you are using variable a of class A, you are reusing the variable a in class B thereby achieving code reusability.

多态性涉及程序如何调用方法取决于它必须执行的事情:在您的示例中,您覆盖 get()的方法类B 的方法 get()的类A 。所以当你创建一个B类和调用方法的实例,你会得到'hi'在控制台'欢迎'

Polymorphism deals with how a program invokes a method depending on the things it has to perform: in your example you are overriding the method get() of class A with method get() of class B. So when you create an instance of Class B and call method get you'll get 'hi' in the console not 'welcome'

这篇关于多态性和继承之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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