C++ 继承和多态的区别

C++ 继承和多态的区别

继承 是一种通过创建一个新类来继承已经存在的类的属性的方式。它支持面向对象编程的代码重用概念,并减少代码的长度。

继承的类型:

  1. 单继承
  2. 多级继承
  3. 多重继承
  4. 混合继承
  5. 分层继承

继承的例子:

#include "iostream"
using namespace std;
 
class A {
    int a, b;
 
public:
    void add(int x, int y)
    {
        a = x;
        b = y;
        cout << (a + b) << endl;
    }
};
 
class B : public A {
public:
    void print(int x, int y)
    {
        add(x, y);
    }
};
 
int main()
{
    B b1;
    b1.print(5, 6);
}
class A:
    def __init__(self):
        self.a = 0
        self.b = 0
 
    def add(self, x, y):
        self.a = x
        self.b = y
        print("addition of a + b is:", self.a + self.b)
 
 
class B(A):
    def sum(self, x, y):
        self.add(x, y)
 
 
# Driver Code
b1 = B()
 
# custom sum
b1.sum(5, 6) 

输出结果:

addition of a+b是:11

这里,类B是派生类,它继承了基类A的属性( add方法 )。

多态:

多态 允许以多种形式或方式执行任务。它适用于函数或方法。多态允许对象在编译时和运行时决定要实现的函数形式。

多态类型:

  1. 编译时多态性(方法重载)
  2. 运行时多态性(方法重写)

多态的例子:

# include "iostream"
using namespace std;
 
class A {
    int a, b, c;
 
public:
    void add(int x, int y)
    {
        a = x;
        b = y;
        cout << "addition of a+b is:" << (a + b) << endl;
    }
 
    void add(int x, int y, int z)
    {
        a = x;
        b = y;
        c = z;
        cout << "addition of a+b+c is:" << (a + b + c) << endl;
    }
 
    virtual void print()
    {
        cout << "Class A's method is running" << endl;
    }
};
 
class B : public A {
public:
    void print()
    {
        cout << "Class B's method is running" << endl;
    }
};
 
int main()
{
    A a1;
 
    // method overloading (Compile-time polymorphism)
    a1.add(6, 5);
 
    // method overloading (Compile-time polymorphism)
    a1.add(1, 2, 3);
 
    B b1;
 
// Method overriding (Run-time polymorphism)
    b1.print();
}
class A {
    int a, b, c;

    public void add(int x, int y)
    {
        a = x;
        b = y;
        System.out.println("a+b的和为:" + (a + b));
    }

    public void add(int x, int y, int z)
    {
        a = x;
        b = y;
        c = z;
        System.out.println("a+b+c的和为:" + (a + b + c));
    }

    public void print()
    {
        System.out.println("Class A的方法正在运行");
    }
};

class B extends A {
    public void print()
    {
        System.out.println("Class B的方法正在运行");
    }

    // 驱动程序
    public static void main(String[] args)
    {
        A a1 = new A();

        // 方法重载(编译时多态)
        a1.add(6, 5);

        // 方法重载(编译时多态)
        a1.add(1, 2, 3);

        B b1 = new B();

        // 方法覆盖(运行时多态)
        b1.print();
    }
}  

输出结果:

a+b的和为:11
a+b+c的和为:6
Class B的方法正在运行

继承和多态的区别:

序号 继承 多态
1. 继承是指创建一个新类(派生类),它继承已经存在类(基类)的特征。 多态是指可同时具有多种形式的事物。
2. 它主要应用于类。 而它主要应用于函数或方法。
3. 继承支持可重用性的概念,减少了面向对象编程的代码长度。 多态允许对象在编译时(重载)和运行时(覆盖)决定实现哪种形式的函数。
4. 继承可以是单一的、混合的、多重的、分层的和多级继承。 它可以是编译时多态(重载)和运行时多态(覆盖)。
5. 它用于模式设计。 它也用于模式设计。
6. 例如: 自行车类可以从双轮车类继承,而后者可以是车类的子类。 例如: 自行车类可以有一个名为set_color()的方法,它会根据输入的颜色将自行车的颜色更改。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程