📜  C ++中多级继承中的构造函数

📅  最后修改于: 2022-05-13 01:55:31.921000             🧑  作者: Mango

C ++中多级继承中的构造函数

构造函数是与类同名的类成员函数。构造函数的主要工作是为类对象分配内存。创建对象时会自动调用构造函数。

多级继承

从另一个派生类派生一个类称为多级继承。 A 类是派生类 B 的基类,B 又作为派生类 C 的基类。 B 类为 A 和 C 之间的继承提供链接,称为中间基类。链 A、B、C 称为继承路径

多级继承

多级继承中的构造函数

示例 1:下面是展示多级继承中构造函数概念的 C++ 程序。

C++
// C++ program to implement
// constructor in multilevel 
// Inheritance
#include
using namespace std;
  
// Base class
class A
{
    public:
        A()
        {
            cout << "Base class A constructor \n";
        }
};
  
// Derived class B
class B: public A
{
    public:
        B()
        {
            cout << "Class B constructor \n";
        }
};
  
// Derived class C
class C: public B
{
    public:
        C()
        {
            cout << "Class C constructor \n";
              
        }
};
  
// Driver code
int main()
{
    C obj;
    return 0;
}


C++
// C++ program to implement 
// multilevel inheritance
#include
using namespace std;
  
// Base class A
class A
{
    public:
        A()
        {
            int a = 5, b = 6, c;
            c = a + b;
            cout << "Sum is:" << 
                     c << endl;
        }
};
  
// Class B
class B: public A
{
    public:
        B()
        {
            int d = 50,e = 35, f;
            f = d - e;
            cout << "Difference is:" <<
                     f << endl;
        }
};
  
// Derived class C
class C: public B
{
    public:
        C()
        {
            int g = 10, h = 20, i;
            i = g * h;
            cout << "Product is:" <<
                     i << endl;            
        }
};
  
// Driver code
int main()
{
    C obj;
    return 0;
}


输出
Base class A constructor 
Class B constructor 
Class C constructor 

示例 2:下面是实现多级继承的 C++ 程序。

C++

// C++ program to implement 
// multilevel inheritance
#include
using namespace std;
  
// Base class A
class A
{
    public:
        A()
        {
            int a = 5, b = 6, c;
            c = a + b;
            cout << "Sum is:" << 
                     c << endl;
        }
};
  
// Class B
class B: public A
{
    public:
        B()
        {
            int d = 50,e = 35, f;
            f = d - e;
            cout << "Difference is:" <<
                     f << endl;
        }
};
  
// Derived class C
class C: public B
{
    public:
        C()
        {
            int g = 10, h = 20, i;
            i = g * h;
            cout << "Product is:" <<
                     i << endl;            
        }
};
  
// Driver code
int main()
{
    C obj;
    return 0;
}
输出
Sum is:11
Difference is:15
Product is:200