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

📅  最后修改于: 2021-05-30 01:59:37             🧑  作者: 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等的更多准备工作,请参阅“完整面试准备课程”