当继承遇上构造函数:
其子类的构造顺序为,父类->子类。就如加盖总得有地基,不可能建造空中楼阁不是;同理,析构顺序相反。
1.无参构造
#include <iostream>
using namespace std;
class A
{
public:
int m_a;
A()
{
cout << "A constructor!" << endl;
m_a = 1;
}
~A()
{
cout << "A Distruct!" << endl;
}
};
class B:public A
{
public:
int m_b;
B()
{
cout << "B constructor!" << endl;
m_b = 1;
}
~B()
{
cout << "B Distruct!" << endl;
}
};
int main()
{
A a1;
cout << sizeof(a1) << endl;
B b1;
cout << sizeof(b1) << endl;
return 0;
}
2.有参函数与const变量
#include <iostream>
using namespace std;
class A
{
public:
int m_a;
A(int a)
{ cout << "A Constructor" << endl;
m_a = a;
}
~A()
{
cout << "A Distruct" << endl;
}
};
class C
{
public:
int m_c;
C(int c)
{
m_c = c;
cout << "C Constructor" << endl;
}
~C()
{
cout << "C Distruct" << endl;
}
};
class B:protected A
{
public:
int m_b;
C c;
const int d;
B(int b):A(1),c(2),d(4)
{
cout << "B Constructor" << endl;
m_b = b;
}
~B()
{
cout << "B Distruct" << endl;
}
};
int main()
{
B b1(2);
return 0;
}
此时其构造函数的顺序变为父类->子类内部对象和const变量(由声明顺序决定)->子类。(注:有参函数的初始化需加入初始化列表)