`
HeLinHang
  • 浏览: 141522 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

类对象作为数据成员

    博客分类:
  • C++
 
阅读更多

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的构造函数最后执行,析构函数的调用相反。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics