头文件包含顺序导致编译出错

shisssasssssss 2016-02-25 10:40:34
time.h
#ifndef _TIME_H
#define _TIME_H

class mydate;

class mytime
{
public:
mytime();
void display(mydate &m);
private:
int hour;
int min;
int sec;
};

#endif


time.cpp
#include <iostream>
#include "time.h"
#include "date.h"

using namespace std;

mytime::mytime():hour(20),min(10),sec(50){

}
void mytime::display(mydate &m){
cout<<m.year<<":"<<m.mon<<":"<<m.day<<endl;
}


date.h
#ifndef _DATE_H

#define _DATE_H

#include "time.h"



class mydate

{

friend void mytime::display(mydate &m);

public:

mydate();



void display();

private:

int year;

int mon;

int day;

};



#endif



date.cpp
#include <iostream>

#include "date.h"



using namespace std;



mydate::mydate():year(2015),mon(10),day(27){



}

void mydate::display(){

cout<<year<<"-"<<mon<<"-"<<day<<endl;

}


main.cpp
#include "time.h"

#include "date.h"



int main()

{

mytime mt;

mydate md;

mt.display(md);



return 0;

}


g++ main.cpp time.cpp date.cpp -o main
报错:
In file included from date.cpp:2:0:
date.h:7:15: error: ‘mytime’ has not been declared
In file included from time.cpp:3:0:
date.h:7:15: error: ‘mytime’ has not been declared
time.cpp:7:1: error: ‘mytime’ does not name a type
time.cpp:10:6: error: ‘mytime’ has not been declared


但是如果将两个cpp文件的#include <iostream>放到date.h和time.h之后,就顺利通过。何解???????
...全文
166 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
幻夢之葉 2016-02-26
  • 打赏
  • 举报
回复
我在VS2008下编译通过 我猜是标准库的的某个文件 (我猜可能是标准库中的 time.h 或者 ctime 文件,具体就不清楚了) 有一个 #ifndef _TIME_H #define _TIME_H 的预编译项 你先 #include <iostream> using namespace std; 可能包含了以上那个预编译项,然后导致你原本的头文件的预编译项 #ifndef _TIME_H 为false 假设你换了包含的顺序,你的time.h先被编译,自然就编译通过了 那么你mytime的声明没有被编译了 解决方法 1:把你time.h中的预编译项的名称改一下试试 2: 不要使用 using namespace std; 直接使用 using std::cout 或者 std::cout << "---" << std::endl; 以上都是猜测,真实原因需要你做以上测试才能验证
shisssasssssss 2016-02-26
  • 打赏
  • 举报
回复
引用 2 楼 jianwen0529 的回复:
我在VS2008下编译通过 我猜是标准库的的某个文件 (我猜可能是标准库中的 time.h 或者 ctime 文件,具体就不清楚了) 有一个 #ifndef _TIME_H #define _TIME_H 的预编译项 你先 #include <iostream> using namespace std; 可能包含了以上那个预编译项,然后导致你原本的头文件的预编译项 #ifndef _TIME_H 为false 假设你换了包含的顺序,你的time.h先被编译,自然就编译通过了 那么你mytime的声明没有被编译了 解决方法 1:把你time.h中的预编译项的名称改一下试试 2: 不要使用 using namespace std; 直接使用 using std::cout 或者 std::cout << "---" << std::endl; 以上都是猜测,真实原因需要你做以上测试才能验证
果然,将_TIME_H改了就过了。
sunshine2572 2016-02-25
  • 打赏
  • 举报
回复
一直没五方头这种问题。不懂,求解

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧