1、基类中没有定义构造函数(就是用默认构造函数)或像下面这种定义一个空的构造函数。此时派生类中的构造函数就照常写
#include<iostream>
using namespace std;
class Base //基类
{
public:
Base() {};
//假如基类中有无参构造函数或默认构造函数(不写这句,使用系统生成的构造函数)
//那么派生类中的有参构造函数就可以正常写
protected:
int i;
int j;
};
class Driver :public Base //派生类
{
public:
Driver(int x, int y);
};
Driver::Driver(int x, int y) //这里的构造函数正常写就行
{
i = x + 1;
j = y + 1;
cout << "调用派生类构造函数" << endl;
cout << "i = " << i << "; j = " << j << endl;
}
int main()
{
Driver Dv(1, 2);
return 0;
}
2、基类中包含有参构造函数
#include<iostream>
using namespace std;
class Base //基类
{
public:
Base(int x, int y);
protected:
int i;
int j;
};
class Driver :public Base //派生类
{
public:
Driver(int x, int y);
};
Base::Base(int x, int y)
{
i = x;
j = y;
cout << "调用基类构造函数" << endl;
cout << "i = " << i << "; j = " << j << endl;
}
//基类中包含有参构造函数的时候,派生类的构造函数要像下面这样写
//在构造函数的后面增加一个冒号,后面是基类的构造函数
//利用初始化列表,对基类的成员进行初始化(基类重载构造函数需要初始化值)
Driver::Driver(int x, int y):Base(x, y)
{
i = x + 1;
j = y + 1;
cout << "调用派生类构造函数" << endl;
cout << "i = " << i << "; j = " << j << endl;
}
int main()
{
Driver Dv(1, 2);
return 0;
}