1
我在同一個項目中有以下文件。 不要打擾閱讀所有的代碼塊,如果你認爲這是沒有必要的, 錯誤消息只出現在ship.cpp在成員函數中,我得到錯誤「無效使用未定義類型'struct(name)' - 'struct(name)'的前向聲明」
的main.cpp
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include "chart.cpp"
#define N 10
using namespace std;
int main()
{
int i,j, flagi=-3, flagj=-3;
int test, ports_count=0, treas_count=0;
chart ***mapp;
mapp=new chart **[N];
for(i=0;i<N;i++){mapp[i]=new chart *[N];}
/*missing code initilazing chart ***mapp */
return 0;
}
chart.cpp
#include <iostream>
#include "ship.cpp"
using namespace std;
class chart{
bool isPort;
int weather;
int treasure;
ship* shipPtr;
public:
chart(){isPort=false; weather=0; treasure=0; shipPtr=NULL;}
bool getPort(){return isPort;}
int getWeather(){return weather;}
int getTreasure(){return treasure;}
ship* getShip(){return shipPtr;}
void setPort(bool port){isPort=port;}
void setWeather(int weath){weather=weath;}
void setTreasure(int treas){treasure=treas;}
void setShip(ship* shp){shipPtr=shp;}
};
和 ship.cpp
#include <iostream>
#define N 10
using namespace std;
class ship{
protected:
string name;
int maxhp, curhp, speed, curtreas, x_pos, y_pos;
public:
friend class chart;
//the line above gives error message " forward declaration of 'struct chart' "
static int shipcount;
ship(){shipcount++;}
string getName(){return name;}
int getMaxhp(){return maxhp;}
int getCurhp(){return curhp;}
int getSpeed(){return speed;}
int getCurtreas(){return curtreas;}
int getX_pos(){return x_pos;}
int getY_pos(){return y_pos;}
bool Move(chart ***mapp){
int x, y, blocked=0;
for(x=x_pos-1;x<=x_pos+1;x++){
if((x>-1) && (x<N)){
for(y=y_pos-1;y<=y_pos+1;y++){
if((y>-1) && (y<N)){
/* the line below gives error message "invalid use of undefined type 'struct chart'"*/
if((!mapp[x][y]->getPort) && (mapp[x][y]->getShip==NULL)){
blocked++;
}
}
}
}
}
if(blocked<2){
return false;
}
/* missing the rest of the body of bool Move cause it is too big */
}
}
編譯器提供以下錯誤消息:
"invalid use of undefined type 'struct chart' " in ship.cpp -> line 39
"forward declaration of 'struct chart' " in ship.cpp -> line 12
這些錯誤爲什麼顯示出來?
我知道代碼可能很複雜,但任何幫助,將不勝感激。
謝謝你的時間。
我將chart.cpp重命名爲chart.h,將chart.h包含在ship.cpp中,並且還將chart.cpp替換爲main中的chart.h,但是當嘗試使用這些更改進行編譯時,編譯將繼續進行而不會停止幾秒鐘後崩潰。 –
編譯器顯示出來的信息:從ship.cpp 2從ship.cpp : 「在文件中包含從ship.cpp:2從chart.h 從chart.h從2從chart.h chart.h:2 from ship.cpp' 這些消息繼續出現太多次,並且消息說: '#include nested deep' –
@thomas_p您需要替換'#include「ship.cpp」 ''在chart.h'中有一個前向聲明'class ship;' – dasblinkenlight