Search code examples
c++undeclared-identifier

C++ undeclared identifier


I want to create a sea ​​battle game. I have two classes: Ship and Cell.

#pragma once
#include"stdafx.h"
#include"Globals.h"
#include<vector>
#include"MCell.h"

 class Ship 
 {

 private:
    int lenght;
    int oriantation;
    vector<Cell*> cells;
    vector<Cell*> aroundCells;

...

#pragma once
#include<vector>
#include"MShip.h"

 class Cell
{

private:
    bool haveShip;
    bool selected;
    bool around;
    int x;
    int y;
    Ship* ship; 

And i have got many error like those:

1>projects\seewar\seewar\mship.h(13): error C2065: 'Cell' : undeclared identifier
1>projects\seewar\seewar\mship.h(13): error C2059: syntax error : '>'
1>projects\seewar\seewar\mship.h(14): error C2065: 'Cell' : undeclared identifier

What's wrong with the code?


Solution

  • Well your problem lies that when you include MCell.h you include MShip.h which references Cell defined in MCell.h. However MShip.h refers to MCell.h which won't get included because of the pragma once. If the pragma once wasn't there then you'd get an inifinite loop that would stack overflow your compiler ...

    Instead you could use a forward declaration.

    ie remove the #include "MCell.h" from MShip.h and replace it with, simply, "class Cell;" All your circular references issues will this go away :)