1.在派生类中,默认基类的构造函数是不被继承的,派生类需要构造自己的构造函数。
PS:在C++11中,定义可以使用using语句来继承基类的构造函数。但它不能初始化派生类新增成员。
2.派生类构造函数需要完成的任务(不继承基类构造函数的情况)
(1)派生类新增成员:派生类定义构造函数初始化;
(2)继承来的成员:c++会自动调用基类构造函数进行初始化;
(3)派生类的构造函数 需要给基类的构造函数传递参数。
3.派生类构造函数与基类构造函数的联系
(1)当基类有默认构造函数时,派生类构造函数可以不向基类构造函数传递参数。
构造派生类的对象时,基类的默认无参构造函数将被调用。
(2) 如需执行基类中带参数的构造函数,派生类构造函数应为基类构造函数提供参数。
4.单继承构造函数
派生类名::派生类名(基类所需的形参,本类成员所需的形参) : 基类名(参数表),本类成员初始化列表
{ //其他初始化;
};
#include "stdafx.h"
#include <iostream>
//#include <cmath>
using namespace std;
class B{
public:
B();
B(int i);
~B();
void print() const;
private:
int b;
};
B::B(){
b = 0;
cout << "B's default constructor called." << endl;
}
B::B(int i){
b = i;
cout << "B's default constructor called." << endl;
}
B::~B()
{
cout << "B's destructor called." << endl;
}
void B::print() const{
cout << b << endl;
}
class C:public B{
public:
C();
C(int i,int j);
~C();
void print()const;
private:
int c;
};
C::C()
{
c = 0;
cout << "C's default constructor called." << endl;
}
C::C(int i, int j) : B(i), c(j)
{
cout << "C's constructor called." << endl;
}
C::~C()
{
cout << "C's destructor called." << endl;
}
void C::print() const
{
B::print();
cout << c << endl;
}
int main()
{
C obj(5, 6);
obj.print();
return 0;
}
4.多继承且有对象成员时派生的构造函数定义语法
派生类名:派生类名(形参表):基类名1(参数),基类名2(参数),……基类名n(参数),本类成员(含对象成员)初始化列表{
//其他初始化
};
5.构造函数的执行顺序
1.调用基类构造函数。顺序按照它们被继承时声明的顺序(从左向右)。
2.对初始化列表中的成员进行初始化。
顺序按照它们在类中定义的顺序。
对象成员初始化时自动调用其所属类的构造函数,由初始化列表提供参数。
3.执行派生类的构造函数体中的内容。
#include "stdafx.h"
#include <iostream>
//#include <cmath>
using namespace std;
class Base1
{//基类Base1,构造函数有参数
public:
Base1(int i)
{
cout << "Constructing Basel" <<'\n'<< i << endl;
}
};
class Base2
{//基类Base2,构造函数有参数
public:
Base2(int j)
{
cout << "Constructing Base2" << '\n' << j << endl;
}
};
class Base3
{//基类Base3,构造函数无参数
public:
Base3()
{
cout << "Constructing Base3*" << endl;
}
};
class Derived :public Base2, public Base1, public Base3
{
// 派生新类Derived,构造函数调用顺序为 先基类构造函数,再调用private内定义顺序构造函数
public://派生类的公有成员
Derived(int a, int b, int c, int d) :Base1(a), member2(d), member1(c),Base2(b){ }
//构造函数执行顺序与这个顺序无关
private: // 派生类的私有成员对象
Base1 member1;
Base2 member2;
Base3 member3;
};
int main(){
Derived obj(1, 2, 3, 4);
return 0;
}