C++ 多重继承中的构造函数
发布: (2025年12月24日 GMT+8 15:43)
2 min read
原文: Dev.to
Source: Dev.to
构造函数
构造函数是与类同名的类成员函数。它的主要作用是初始化类对象。创建对象时会自动调用构造函数。
多重继承
多重继承是 C++ 的一项特性,允许一个类从两个或更多基类派生。基类的构造函数会按照它们在继承列表中出现的顺序被调用。
多重继承的语法
class S : public A1, virtual A2
示例 1
下面是一个演示多重继承中构造函数的 C++ 程序。
// C++ program to implement constructor in multiple inheritance
#include <iostream>
using namespace std;
class A1 {
public:
A1() {
int a = 20, b = 35, c;
c = a + b;
cout << "Sum is: " << c << endl;
}
};
class A2 {
public:
A2() {
int x = 50, y = 42, z;
z = x - y;
cout << "Difference is: " << z << endl;
}
};
class S : public A1, virtual A2 {
public:
S() : A1(), A2() {
int r = 40, s = 8, t;
t = r * s;
cout << "Product is: " << t << endl;
}
};
int main() {
S obj;
return 0;
}
输出
Difference is: 8
Sum is: 55
Product is: 320
复杂度分析
- 时间复杂度: O(1)
- 辅助空间: O(1)