两个类相互包含的问题

1,问题介绍:

在  Date.h 文件中声明了Date这个类,

在  Date.cpp 文件中定义了Date 这个类

在 Time.h 文件中声明 Time 这个类,

在 Time.cpp 中定义Time这个类。


在Date类中包含一个Time 类对象,

在Time类中包含一个Date类对象。

那么,Date.h中必须要包含Time.h  ,  Time.h中必须要包含Date.h

假设首先编译Date.cpp ,就会调用Date.h ,但是Date.h 中又包含了Time.h ,Time.h 中又包含了 Date.h  ,形成死循环,重复调用

2,代码举例说明

Date.h

#include<iostream>
using namespace std;
#include"Time.h"

class Date
{
public:
	Date(int year=2018,int month=6,int day=14);

	void PrintDate();

//private:
	int _year;
	int _month;
	int _day;

	Time _d;     //包含Time类对象
  

};


Date.cpp 

#include"Date.h"

Date:: Date(int year,int month,int day)
:_year(year)
,_month(month)
,_day(day)

{}
  

void Date:: PrintDate()
{
  cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
  cout<<_d._hour<<"-"<<_d._minute<<"-"<<_d._second<<endl;
}

Time.h


#include<iostream>
using namespace std;
#include"Date.h"

class Time
{
public:

	Time(int hour=15,int minute=23,int second=33);

	void printTime();

//private:
	int _hour;
	int _minute;
	int _second;
	Date _t;     //包含Date类对象
};


Time.cpp 

#include"Time.h"

Time::Time(int hour,int minute,int second)
:_hour(hour)
,_minute(minute)
,_second(second)
{}

void Time::printTime()
{
   cout<<_t._year<<"-"<<_t._month<<"-"<<_t._day<<endl;
  cout<<_hour<<"-"<<_minute<<"-"<<_second<<endl;
}

执行编译的结果


深度 = 1024 : 这个报错说明头文件重复包含,达到最大高度

3,解决方法

1>使用 #pragma once  来对头文件的编译次数进行限制

结果:



依然报错,没有从根本上解决问题

2>使用延后创建的方法

方法介绍:

先不创建类,而是先创建一个类的指针,类的具体创建放在构造函数中进行,

因为创建一个类的指针不需要包含头文件,只需要进行声明,让文件知道有这个类型

举例代码说明:

Date.h

#include<iostream>
using namespace std;
class Time;//对类进行声明,让文件知道有这个类型

class Date
{
public:
	Date(int year=2018,int month=6,int day=14);

	void PrintDate();

//private:
	int _year;
	int _month;
	int _day;

	Time* _d;//先创建一个类的指针
  

};


Date.cpp

#include"Date.h"
#include"Time.h"//要分配一个Time对象的空间就要知道Time的结构
#include<malloc.h>

Date:: Date(int year,int month,int day)
:_year(year)
,_month(month)
,_day(day)

{
 Time* _d=(Time*)malloc(sizeof(Time));//类的具体创建放在构造函数中进行
}
  

void Date:: PrintDate()
{
  cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
  cout<<_d->_hour<<"-"<<_d->_minute<<"-"<<_d->_second<<endl;
}

Time.h


#include<iostream>
using namespace std;
class Date;    //对类进行声明,让文件知道有这个类型


class Time
{
public:

	Time(int hour=15,int minute=23,int second=33);

	void printTime();

//private:
	int _hour;
	int _minute;
	int _second;
	Date* _t;//先创建一个类的指针
};


Time.cpp

#include"Time.h"
#include"Date.h"//要分配一个Date对象的空间就要知道Date的结构
#include<malloc.h>

Time::Time(int hour,int minute,int second)
:_hour(hour)
,_minute(minute)
,_second(second)

{
    Date* _t=(Date*)malloc(sizeof(Date));//类的具体创建放在构造函数中进行
}

void Time::printTime()
{
   cout<<_t->_year<<"-"<<_t->_month<<"-"<<_t->_day<<endl;
  cout<<_hour<<"-"<<_minute<<"-"<<_second<<endl;
}

结果:


完美解决





猜你喜欢

转载自blog.csdn.net/wm12345645/article/details/80705540