考試大編輯整理C++編程知識
有一個Road類,有一個Intersection類,Road類中要含有兩個節(jié)點Intersection的信息, Intersection要有相鄰路的信息列表。
于是Road.h中這樣定義:
class Road
...{
private:
Intersection * from;
Intersection * to;
public:
........
}
Intersection.h中這樣定義:
class Intersection
...{
private:
list roadNext;
public:
.......
}
很可惜這樣編譯通不過,編譯器會報找不到類型錯誤。
于是在Intersection類中添加一行代碼
class Road;
在Road.h中導(dǎo)入Intersection的文件#include\"Intersection.h\"
這樣編譯應(yīng)該沒有問題。(如果函數(shù)中沒有出現(xiàn)Road類型或者 Intersection類型的話)
但如果函數(shù)中有Road類型或者 Intersection類型又怎么辦呢?
創(chuàng)建Road.cpp和Intersection.cpp文件
在*.h中只是寫函數(shù)的聲明,在cpp文件中寫函數(shù)定義,并導(dǎo)入兩個.h文件。例如:
#include\"Road.h\"
#include\"Intersection.h\"
void Intersection::InsertRoad(Road * r)
...{
roadNext.insert(roadNext.begin,r);
}編譯。。。通過
有一個Road類,有一個Intersection類,Road類中要含有兩個節(jié)點Intersection的信息, Intersection要有相鄰路的信息列表。
于是Road.h中這樣定義:
class Road
...{
private:
Intersection * from;
Intersection * to;
public:
........
}
Intersection.h中這樣定義:
class Intersection
...{
private:
list
public:
.......
}
很可惜這樣編譯通不過,編譯器會報找不到類型錯誤。
于是在Intersection類中添加一行代碼
class Road;
在Road.h中導(dǎo)入Intersection的文件#include\"Intersection.h\"
這樣編譯應(yīng)該沒有問題。(如果函數(shù)中沒有出現(xiàn)Road類型或者 Intersection類型的話)
但如果函數(shù)中有Road類型或者 Intersection類型又怎么辦呢?
創(chuàng)建Road.cpp和Intersection.cpp文件
在*.h中只是寫函數(shù)的聲明,在cpp文件中寫函數(shù)定義,并導(dǎo)入兩個.h文件。例如:
#include\"Road.h\"
#include\"Intersection.h\"
void Intersection::InsertRoad(Road * r)
...{
roadNext.insert(roadNext.begin,r);
}編譯。。。通過