C ++实例中的多重多层次和分层继承


C ++中的多个多级和分层继承示例是今天的主题。在开始使用Multiple,Multilevel和Hierarchical继承之前,了解继承是必不可少的。继承允许在派生类中使用基类的属性。这是面向对象编程的必要特征。用更多的技术词来说,我们可以说当基类的对象自动获取父对象的所有属性时,我们可以在子对象的帮助下访问父类的特征,那么它就是一个继承。

内容概述

  • 1 C ++中的多重继承
  • 2#C ++中的多级继承
  • C ++中的3 #Hierarchical继承
      • 3.0.1#C ++中的多重,多级和分层继承的程序

C ++中的多重继承

当派生类派生自多个基类时,它被称为多重继承。

多重继承

在上面的例子中,我们可以看到孩子来自父母。

在函数重写时发生的多重继承存在歧义。例如,双父类具有相同的功能,在子类中不会被覆盖,如果我们尝试使用子类的对象调用该函数,它会在编译器错误中显示,因为编译器不知道哪个函数打电话。 (最后的示例程序)。

C ++中的#Multilevel继承

当一个类继承另一个类的属性(另一个类进一步继承)时,它被称为多级继承。

C ++中的多级继承

在上面的例子中,我们可以看到孩子来自父母,而父母则来自祖父母;因此,它们表现出多层次的继承。

继承级别可以根据关系扩展到任何数量。

最后参见示例以便更好地理解。

C ++中的#Hierarchical继承

它是一种继承,我们通常从特定的基类派生多个派生类。

多级多层次和分层继承

在上面的例子中,我们可以看到Civil,CSE和Mechanical是从工程本身分层派生的,它显示了层次继承。

#C ++中的多个,多级和分层继承的程序

编写程序以显示多重继承机制。

#include  using namespace std;  class patna { //Creating base class of patna public:   patna()   {     cout << "Hello I am from base class of Patna !! " << endl;   } };  class delhi { public:   delhi()   {     cout << "Hello I am from base class of Delhi" << endl; //creating base class of delhi   } };  class check : public patna, public delhi //derived class of two base classes { public:   void check_fun()   {     cout << "hello I am derived class function" << endl;   } };  int main() {   check obj;   obj.check_fun();   return 0; }

请参阅以下输出。

多重继承计划

编写程序以显示多级继承的机制。

#include  using namespace std;  class city { public:   city()   {     cout << "Hello I am the 1st base class of cities" << endl;   } }; class delhi : public city { public:   delhi()   {     cout << "Hello I am the capital of India Delhi" << endl;   } }; class location : public delhi { public:   location()   {     cout << "I am vasant kunj(location) in Delhi" << endl;   } };  // main function int main() {   location obj;   return 0; }

请参阅以下输出。

多级继承程序

编写一个程序来显示Hierarchical Inheritance的机制。

#include  using namespace std;  class city { public:   city()   {     cout << "I am the base class of cities" << endl;   } };  class delhi : public city { public:   void check_1()   {     cout << "I am the capital of India Delhi" << endl;   } };  class mumbai : public city { public:   void check_2()   {     cout << "I am the city of dreams Mumbai" << endl;   } };  int main() {   delhi obj1;   mumbai obj2; //constructor will be called two times as both the objects will call the constructor of the base class.   obj1.check_1();   obj2.check_2();    return 0; }

请参阅以下输出。

分层继承程序

最后,C ++示例中的多重多级和分层继承已经结束。

资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Ankit Lathiya所有,未经许可,不得转载
你可能还喜欢