在成员函数中,我得到错误“未定义类型 'struct (name)' 的无效使用 - 'struct (name)' 的前向声明”

In member function I get the error " invalid use of undefined type 'struct (name)' - forward declaration of 'struct (name)' "

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

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

为什么会出现这些错误?

我知道代码可能很复杂,但如有任何帮助,我们将不胜感激。

感谢您的宝贵时间。

此代码无法编译的原因是您的 ship.cpp 文件需要 chart class 的定义才能使用其成员。你没有提供这个定义,提示编译器报错。

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

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

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