一、构建孙子对象时,调用顺序如下:
- 1.基类
- 2.父类
- 3.成员
- 4.自身
- 基类有成员变量时那么孙子儿子自己都得初始化
- 成员有成员变量时,自己也得给其初始化
#include "String.h"
#include <iostream>
using namespace std;
class Base{
protected:
String m_name;
public:
Base(const String& name):m_name(name) {
cout <<"Base construcr:" << this << endl;
}
~Base(){
cout <<"Base distrucr:" << this << endl;
}
};
class Derive:public Base{
public:
Derive(const String& name):Base(name){
cout <<"Derive construcr:" << this << endl;
}
~Derive(){
cout <<"Derive distrucr:" << this << endl;
}
};
class Member{
//String m_name;
public:
Member(/*const String& name*/)/*:m_name(name)*/{
cout <<"Member construcr:" << this << endl;
}
~Member(){
cout <<"Member distrucr:" << this << endl;
}
};
class SubDerive : public Derive{
public:
SubDerive(const String& name):Derive(name)/*,m(name)*/{
cout <<"SubDerive construcr:" << this << endl;
}
~SubDerive(){
cout <<"SubDerive distrucr:" << this << endl;
}
void Print()const{
cout << m_name << endl;
}
private:
Member m;
};
int main(){
SubDerive d("zhangsan");
d.Print();
}
二、结果
[kiosk@foundation89 C++]$ vim String.h
[kiosk@foundation89 C++]$ vim String.cpp
[kiosk@foundation89 C++]$ g++ construct_test.cpp String.cpp
[kiosk@foundation89 C++]$ ./a.out
Base construcr:0x7fff6e4b65f0
Derive construcr:0x7fff6e4b65f0
Member construcr:0x7fff6e4b65f8
SubDerive construcr:0x7fff6e4b65f0
zhangsan
SubDerive distrucr:0x7fff6e4b65f0
Member distrucr:0x7fff6e4b65f8
Derive distrucr:0x7fff6e4b65f0
Base distrucr:0x7fff6e4b65f0
[kiosk@foundation89 C++]$