C++中多重继承的构造函数
构造函数是与类同名的类成员函数。构造函数的主要工作是为类对象分配内存。创建对象时会自动调用构造函数。
多重继承:
多重继承是 C++ 的一个特性,其中一个类可以派生自多个(两个或更多)基类。继承类的构造函数按照它们被继承的顺序被调用。
多重继承的语法:
class S: public A1, virtual A2
{
….
};
Here,
A2(): virtual base constructor
A1(): base constructor
S(): derived constructor
示例 1 :下面是展示多重继承中构造函数概念的 C++ 程序。
C++
// C++ program to implement
// constructor in multiple
// inheritance
#include
using namespace std;
class A1
{
public:
A1()
{
cout << "Constructor of the base class A1 \n";
}
};
class A2
{
public:
A2()
{
cout << "Constructor of the base class A2 \n";
}
};
class S: public A1, virtual A2
{
public:
S(): A1(), A2()
{
cout << "Constructor of the derived class S \n";
}
};
// Driver code
int main()
{
S obj;
return 0;
}
C++
// C++ program to implement
// constructors in multiple
// inheritance
#include
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;
}
};
// Driver code
int main()
{
S obj;
return 0;
}
输出
Constructor of the base class A2
Constructor of the base class A1
Constructor of the derived class S
示例 2 :下面是展示多重继承中构造函数概念的 C++ 程序。
C++
// C++ program to implement
// constructors in multiple
// inheritance
#include
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;
}
};
// Driver code
int main()
{
S obj;
return 0;
}
输出
Difference is:8
Sum is:55
Product is:320