在类的使用中,默认的构造函数不带任何参数,但是也会因为需要而使用带参数的构造函数。
在带参的构造函数中,是如何继承的呢,这里我们通过使用基类,子类,孙类的两重继承来观察,如何给带参构造函数赋值的。
首先构造带参的基类构造函数:
class Base:
{
public:
Base(int num1, int num2);// 基类Base的带参构造函数
...
}
创建子类Child,使子类继承Base类
class Child : public Base
{
public:
// 子类Child的带参构造函数,其中将num1,num2赋值给了Base的带参构造函数
Child(int num1, int num2, int num3, int num4) :Base(num1, num2)
...
}
创建孙类Grandson,使孙类继承了子类Child
class Grandson :public Child
{
public:
// 孙类Grandson的带参构造函数,其中将num1,num2,num3,num4赋值给了Child的带参构造函数
Grandson(int num1, int num2, int num3,
int num4, int num5, int num6) : Child(num1, num2, num3, num4)
...
}
示例程序:
// Len2024_0106_01.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
class Base
{
private:
int m_nNum1;
int m_nNum2;
public:
Base(int num1, int num2)
{
m_nNum1 = num1;
m_nNum2 = num2;
}
void Show()
{
cout << "Base Class: m_nNum1="<< m_nNum1<<",m_nNum2="<< m_nNum2 << endl;
}
};
class Child : public Base
{
private:
int m_nNum3;
int m_nNum4;
public:
Child(int num1, int num2, int num3, int num4) :Base(num1, num2)
{
m_nNum3 = num3;
m_nNum4 = num4;
}
void Show()
{
Base::Show();
cout << "Child Class: m_nNum3=" << m_nNum3 << ",m_nNum4=" << m_nNum4 << endl;
}
};
class Grandson :public Child
{
private:
int m_nNum5;
int m_nNum6;
public:
Grandson(int num1, int num2, int num3, int num4, int num5, int num6) :Child(num1, num2, num3, num4)
{
m_nNum5 = num5;
m_nNum6 = num6;
}
void Show()
{
Child::Show();
cout << "Grandson Class: m_nNum5=" << m_nNum5 << ",m_nNum6=" << m_nNum6 << endl;
}
};
int main()
{
Grandson gChild = Grandson(1001,2001,3001,4001,5001,6001);
gChild.Show();
}
执行结果: