📜  C++中单继承和多继承的区别

📅  最后修改于: 2021-09-10 02:58:54             🧑  作者: Mango

单一继承:
单继承是派生类以公开、私有或保护方式继承单个基类的继承。在单一继承中,派生类使用单一基类的特性或成员。根据继承父类或基类时指定的访问说明符,派生类或子类可以访问这些基类成员。

句法:

Class DerivedClass_name : access_specifier Base_Class
{
    //Class's Body 
}; 

单一继承的例子:

#include
using namespace std;
class A {
public:
    int k = 1000;
    float salary = 80000;
};
class B : public A {
public:
    float bonus = 8000;
    void ts()
    {
        cout<<"Total salary.."<<(salary + bonus)<

输出:

Salary: 80000
Bonus: 8000
total salary..88000 

在本例中,A 是基类或父类,B 是派生类或子类。

多重继承:
多重继承是派生类获得两个或多个基类的继承。在多重继承中,派生类可以使用继承基类的联合特性。每个基类都由派生类通过通知每个基类的单独访问说明符来继承。根据继承父类或基类时指定的访问说明符,派生类或子类可以访问基类成员。

句法:

Class DerivedClass_name : access_specifier Base_Class1, access_specifier Base_Class2
{
    //Class's Body 
}; 

多重继承的例子:

#include
using namespace std;
class A {
public:
    float salary = 80000;
};
  
class B {
public:
    float bonus = 8000;
};
  
class C : public A, public B {
public:
    void ts()
    {
        cout<<"Total salary.."<<(salary + bonus)<

输出:

Total salary..88000 

在这个例子中,A 和 B 是基类,C 是派生类。

单继承和多继承的区别:

S.NO Single inheritance Multiple inheritance
1. Single inheritance is one in which the derived class inherits the single base class. Whereas multiple inheritance is one in which the derived class acquires two or more base classes.
2. In single inheritance, the derived class uses the features of the single base class. While in multiple inheritance, the derived class uses the joint features of the inherited base classes.
3. Single inheritance requires small run time as compared to multiple inheritance due to less overhead. While multiple inheritance requires more run time time as compared to single inheritance due to more overhead.
4. Single inheritance is a lot of close to specialization. In contrast, multiple inheritance is a lot of close to generalization.
5. Single inheritance is implemented as Class DerivedClass_name : access_specifier Base_Class{};. While multiple inheritance is implemented as Class DerivedClass_name : access_specifier Base_Class1, access_specifier Base_Class2, ….{}; .
6. Single inheritance is simple in comparison to the multiple inheritance. While multiple inheritance is complex in comparison to the single inheritance.
7. Single inheritance can be implemented in any programming language. C++ supports multiple inheritance but multiple inheritance can’t be implemented in any programming language(C#, Java doesn’t support multiple inheritance).

想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程