Father.h
#ifndef FATHER_H
#define FATHER_H
#include"Mother.h"
class Father
{
public:
Father(int a,int b);
~Father(void);
private:
Mother m;
int i;
};
#endif
Father.cpp
#include "Father.h"
#include<iostream>
using namespace std;
Father::Father(int a,int b):m(a,b),i(a)
{
cout<<"father constructed!"<<endl;
m.show();
cout<<"I:"<<i<<endl;
}
Father::~Father(void)
{
cout<<"father deconstructed!"<<endl;
}
Mother.h
#pragma once
class Mother
{
public:
Mother(int a,int b);
~Mother(void);
void show();
private:
int a;
int b;
};
Mother.cpp
#include "Mother.h"
#include<iostream>
using namespace std;
Mother::Mother(int a,int b)
{
this->a=a;
this->b=b;
cout<<"mother constructed!"<<endl;
}
Mother::~Mother(void)
{
cout<<"mother deconstructed!"<<endl;
}
void Mother::show()
{
cout<<"A:"<<a<<"B:"<<b<<endl;
}
Main.cpp
#include<iostream>
#include"Father.h"
using namespace std;
int main()
{
Father f(1,2);
return 0;
}
先调用Mother的构造函数,然后调用Father的构造函数,然后调用Father的析构函数,最后调用Mother的析构函数
当调用X::X()的时候,按照对象成员在类中定义的顺序,依次调用他们的构造函数,X的构造函数最后执行,析构函数的调用相反。