头文件包含顺序导致编译出错
time.h
time.cpp
date.h
date.cpp
main.cpp
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之后,就顺利通过。何解???????
#ifndef _TIME_H
#define _TIME_H
class mydate;
class mytime
{
public:
mytime();
void display(mydate &m);
private:
int hour;
int min;
int sec;
};
#endiftime.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之后,就顺利通过。何解???????
...全文


