在成员函数中我得到错误"无效使用未定义类型&#struct; name(名称)' - ' struct(name)'的前向声明"

时间:2015-01-03 04:56:34

标签: c++ struct forward-declaration member-functions

我在同一个项目中有以下文件。 如果您认为没有必要,请不要费心阅读所有代码块, 错误消息仅出现在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

为什么会出现这些错误?

我知道代码可能很复杂,但任何帮助都会受到赞赏。

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

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

由于类chart的所有成员都已在类声明中定义,因此您可以将chart.cpp重命名为chart.h,并在#include中为其添加ship.cpp {1}}档案:

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

同时使用chart.cpp替换main中的名称chart.h