gpt4 book ai didi

c++ - 在成员函数中我得到错误 "invalid use of undefined type ' struct (name )' - forward declaration of ' struct (name )' "

转载 作者:太空宇宙 更新时间:2023-11-04 11:22:40 27 4
gpt4 key购买 nike

我在同一个项目中有以下文件。如果您认为没有必要,请不要费心阅读所有代码块,错误消息仅出现在 ship.cpp 中

主要.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;
}

图表.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;}
};

和船.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

为什么会出现这些错误?

我知道代码可能很复杂,但我们将不胜感激。

感谢您的宝贵时间。

最佳答案

此代码无法编译的原因是您的 ship.cpp 文件需要定义 chart 类才能使用其成员。您未能提供此定义,导致编译器报错。

由于类chart的所有成员都在类声明中定义,您可以将chart.cpp重命名为chart.h,并在您的 ship.cpp 文件中为其添加一个 #include:

#include <iostream>
#include "chart.h"
#define N 10
... // The rest of ship.cpp code

同时将 main 中的名称 chart.cpp 替换为 chart.h

关于c++ - 在成员函数中我得到错误 "invalid use of undefined type ' struct (name )' - forward declaration of ' struct (name )' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27751872/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com