Ошибка компилятора c2061

Синтаксическая ошибка: идентификатор «Player». Файл mob.h ст 40
Гуглить пробовал. Ответ так и не нашел

player.h:

#pragma once
#include "Weapon.h"
#include "Mob.h"

class Player
{
public:
	int health, armor, exp, mana;
	int currentHealth, currentArmor, currentMana, toNextLvlExp, balance;
	int missChanceBody, missChanceHead, missChanceLegs;

	Weapon sword;
	Weapon magicStick;

	Player(int _health, int _armor, const Weapon& _sword, const Weapon& _magicStick);
	int takePhysicalDamage(Mob& m);
};

mob.h:

#pragma once
#include <string>
#include "Player.h"

using namespace std;

class Mob
{
public:
	enum mobType {
		PHYSIC,
		MAGIC
	};

	enum attackDir {
		HEAD,
		BODY,
		LEGS
	};

	int health, armor, magicResistance, shockResistance;
	int currentHealth, damage, spreadDamage;
	string name;
	mobType attackType;

	

	/**
	 * Конструктор класса Mob.
	 * Принимает 3 аргумента
	 * _health - здоровье моба
	 * _magicResistance - защита от магического урона
	 * _shockResistance - защита от физического урона
	 * _damage - урон
	 * _spreadDamage - Разброс урона
	 * _name - Имя моба
	 * type - тип атаки моба
	 */
	Mob(int _health, int _magicResistance, int _shockResistance, int _damage, int _spreadDamage, string _name, mobType type);
	int takePhysicalDamage(Player* player, attackDir dir);
	int takeMagicalDamage(Player* player, attackDir dir);
};

I try to reference a struct from another class in my code and it gives me an error, saying I have a syntax problem.

#pragma once

#include "Definitions.h"

#include "GV.h"
#include "UI.h"
#include "Tile.h"
#include "Item.h"

class Figure {
public:
    //Figure index
    struct FIGURE_TYPE {
        //Where to crop the image from
        SDL_Rect crop;
        int x;
        int y;
    };

    //The game figure
    FIGURE_TYPE figure_index[FIGURE_COUNT];

    //The figure array
    int figure_array[MAP_HEIGHT / 64][MAP_WIDTH / 64];

    //Functions
    Figure ( void );
    bool draw_figures ( SDL_Surface* screen, SDL_Surface* figures, SDL_Rect camera, Figure::FIGURE_TYPE figure_spec[FIGURE_COUNT] );
};

That’s the struct in Figure.h,

#pragma once

#include "Definitions.h"

#include "GV.h"
#include "Tile.h"
#include "Item.h"
#include "Figure.h"

class UI {
public:
    UI ( void );
    void set_camera ( SDL_Rect& camera, Figure::FIGURE_TYPE figure_spec[FIGURE_COUNT] );
    bool draw_map ( SDL_Surface* screen, SDL_Rect& camera, SDL_Surface* tiles, SDL_Surface* figures, Figure::FIGURE_TYPE figure_spec[FIGURE_COUNT] );
    bool draw_status ( void );
};

And that is where I reference it, from another header file called UI.h. I know there is a problem with referencing structures, I just don’t know how to fix it. Simple problem, any one wanna help?

The problem is not that Figure Type is declared outside of Figure.h, or that it is private as opposed to public.

Error Reports

Error 1 error C2653: ‘Figure’ : is not a class or namespace name c:\users\jim\documents\c++\roguelike\roguelike\ui.h 13 1 roguelike

Error 3 error C2653: ‘Figure’ : is not a class or namespace name c:\users\jim\documents\c++\roguelike\roguelike\ui.h 14 1 roguelike

Error 2 error C2061: syntax error : identifier ‘FIGURE_TYPE’ c:\users\jim\documents\c++\roguelike\roguelike\ui.h 13 1 roguelike

Error 4 error C2061: syntax error : identifier ‘FIGURE_TYPE’ c:\users\jim\documents\c++\roguelike\roguelike\ui.h 14 1 roguelike

I hate to post something so subtle, but this has me completely stumped on what I am doing wrong:
When I compile, it’s not liking Class Simulator at all. I get the error

syntax error : identifier 'Simulator'

at every instance of Simulator I use inside the DOCO header file. It also does this for my Pellet struct. The code was working completely fine until I started adding functions that work with the Simulator class inside DOCO.h.
The Simulator class uses the DOCO struct and the DOCO struct is using class Simulator. Is that a problem? Maybe I used included my headers wrong?

Here is a link to the error I get if it helps: http://msdn.microsoft.com/en-us/library/yha416c7.aspx

#include <iostream>
#include <conio.h>
#include <string>
#include "Simulator.h"   //<---Has a chain of includes for other header files
int main()
{
    RandomNumberGen R;
    Simulator S;
    Pellet P;
    DOCO D;

    system("pause");
    return 0;
}

Header Files:
Simulator.h

#pragma once
#include <iostream>
#include <stdio.h>
//#include <conio.h>
#include <vector>
#include "Pellet.h"
#include "DataParser.h"
#include "DOCO.h"
#include "RandomNumberGen.h"
#include "Cell.h"
#include "Timer.h"

using namespace std;

class Simulator
{
private:
    int s_iDocoTotal;
    int s_iPelletTotal;
    int s_iGridXComponent;
    int s_iGridYComponent;
    int tempX;
    int tempY;

    //Pellet P;
    //DOCO D;


    static const unsigned int s_iNumOfDir=8;


public:
    Simulator();
    ~Simulator();

    //int GenerateDirection();
    void InitiateDOCO(RandomNumberGen *R, DOCO *D, vector<DOCO>&);  //
    void SpreadFood(RandomNumberGen *R, Pellet *P, vector<Pellet>&, const int x, const int y);      //
    void AddPellet(Pellet *P, RandomNumberGen *R);          //
    void CheckClipping(Pellet *P, RandomNumberGen *R);      //
    void CheckPellets(Pellet *P, RandomNumberGen *R);       //
    void CreateGrid(int x, int y);//
    int GetGridXComponent();    //
    int GetGridYComponent();    //
    int GetDocoTotal();
    vector<DOCO> docoList;                  //Holds the Doco coordinates
    vector<Pellet> pelletList;              //!!Dont use this!! For data import only
    vector<vector<int> > pelletGrid;    //Holds X-Y and pellet count
    char **dataGrid;        //Actual array that shows where units are

    Simulator(const int x, const int y) : 
                s_iGridXComponent(x), 
                s_iGridYComponent(y),
                pelletGrid(x, vector<int>(y)){}
};

DOCO.h

#pragma once
#include <iostream>
#include <stdio.h>
#include <vector>
#include "Simulator.h"
//#include "DataParser.h"



using namespace std;

struct DOCO
{
private:
    int d_iXLocation;
    int d_iYLocation;
    int d_iEnergy;
    int d_iMovement;
    int d_iTemp;
    //Simulator S;
    //RandomNumberGen R;
    //Pellet P;
    enum Direction { NORTH, SOUTH, EAST, WEST, NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST};


public:
    DOCO();
    ~DOCO();
    //int a is the position in docoList to reference DOCO
    int GoNorth(Simulator *S, int a);
    int GoSouth(Simulator *S, int a);
    int GoEast(Simulator *S, int a);
    int GoWest(Simulator *S, int a);
    int GoNorthWest(Simulator *S, int a);
    int GoNorthEast(Simulator *S, int a);
    int GoSouthWest(Simulator *S, int a);
    int GoSouthEast(Simulator *S, int a);

    //int a is the position in docoList to reference DOCO
    void Sniff(Simulator *S, RandomNumberGen *R, int a);        //Detects DOCOs and food
    void Reroute(Simulator *S, RandomNumberGen *R, int a);  //Changes DOCO direction
    void SetDOCO(int tempX, int tempY, int tempEnergy, int tempMovement);
    int GetEnergy();    //
    int SetEnergy();
    int SetMovement();
    int GetMovement();  //
    int GetXLocation(); //
    int GetYLocation(); //
    void SetXLocation(int d_iTemp);
    void SetYLocation(int d_iTemp);
    void EatPellet(Pellet *P, Simulator *S, int a);//ADD DOCO ARGUMENT / DONT OVERLAP DOCO AND PELLETS
    void MoveDoco(Simulator *S, int a);
    void Death();
};

  • Remove From My Forums
  • Question

  • I have a complex application that we are porting to Visual Studio 8 and have run into this error with no solution so far.

    Note that the error producing code resides in the file: 

    «D:\Program Files\Microsoft Visual Studio 8\VC\INCLUDE\stdlib.h

    This simple unit test demonstrates the problem as succinctly as possible I think

    // foo.cpp : Defines the entry point for the console application.

    //

    #include «stdafx.h»

    template < _CountofType, size_t _SizeOfArray>

    char (*__countof_helper( _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];

    int _tmain(int argc, _TCHAR* argv[])

    {

          printf( «hello world\n» );

          return 0;

    }

    1>—— Build started: Project: foo, Configuration: Debug Win32 ——

    1>Compiling…

    1>foo.cpp

    1>c:\documents and settings\jlarson\my documents\visual studio 2005\projects\foo\foo\foo.cpp(6) : error C2061: syntax error : identifier ‘_CountofType’

    1>c:\documents and settings\jlarson\my documents\visual studio 2005\projects\foo\foo\foo.cpp(7) : fatal error C1903: unable to recover from previous error(s); stopping compilation

    1>Build log was saved at «file://c:\Documents and Settings\jlarson\My Documents\Visual Studio 2005\Projects\foo\foo\Debug\BuildLog.htm»

    1>foo — 2 error(s), 0 warning(s)

    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Answers

  • OK, this is odd. I have those lines in my header files and I never seen these errors.

    So lets get back to you first example, if you add typename does it compile ?

    The only thing that comes to my mind now is that is something wrong with the C++ compiler, something like using an older version. Do you have another version of Visual Studio installed ? Or another C++ compiler ?

  • You can try to put the following lines in a Visual C++ project and compile to see what happens:

    #if _MSC_VER < 1400

    #error You are using an old compiler.

    #endif

    You’ll get an error if you are using a compuler other than the Visual C++ 2005 compiler (which version is > 14.0).

    But since you say that the code from your first post compiles with typename added I doubt it’s the compiler. Maybe it’s a header conflict with Visual C++ 6.0. There was an option when installing Visual C++ 6.0 to set environment variables like PATH, INCLUDE and LIB to point to VC++ 6.0 directories. If that is in effect maybe VC++ 2005 includes some old header from VC++ 6.0 (altough from the error messages you have posted it seems that it is using the correct include dir but maybe it’s getting just one header from the old dir).

  • Thank you,  I had to plow ahead and haven’t tried your suggestion as the workaround worked well enough for me.

     my workaround was to do this:

    #ifndef _countof
    #define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0]))
    #endif

    #ifndef SORTPP_PASS
    #define SORTPP_PASS
    #endif

Я пытаюсь изучать C ++, однако, параметр метода, который у меня есть в моем собственном классе, ведет себя неправильно. Когда он использует dataType типа int, он отлично работает без ошибок, но когда я пытаюсь изменить его на «string» dataType, программа вылетает с этой ошибкой.

Ошибка 1 ошибка C2061: синтаксическая ошибка: идентификатор ‘строка’ в файле temp.h ln
8 цв 1

Я использую следующие классы:

РАБОЧИЙ КОД
TesterClass.cpp // Точка входа

#include "stdafx.h"#include "Temp.h"
int _tmain(int argc, _TCHAR* argv[])
{
Temp tmp;
tmp.doSomething(7);

return 0;
}

Temp.h

#pragma once

class Temp
{
public:
Temp();

void doSomething(int blah);
};

Temp.cpp

#include "stdafx.h"#include "Temp.h"
#include <iostream>
#include <string>

using std::string;

Temp::Temp()
{
std::cout << "Entry" << std::endl;
string hi;
std::cin >> hi;
std::cout << hi << std::endl;
}

void Temp::doSomething(int blah)
{
std::cout << blah;
}

Сломанный код
Temp.h

#pragma once

class Temp
{
public:
Temp();

void doSomething(string blah);
};

Temp.cpp

#include "stdafx.h"#include "Temp.h"
#include <iostream>
#include <string>

using std::string;

Temp::Temp()
{
std::cout << "Entry" << std::endl;
string hi;
std::cin >> hi;
std::cout << hi << std::endl;
}

void Temp::doSomething(string blah)
{
std::cout << blah;
}

Когда я настраиваю параметр «blah» на строку, как в файле .h, так и в файле .cpp, возникает проблема.

Я огляделся, но ни один из ответов, похоже, не решил мою проблему. Я очень хотел бы помочь в этом, я вне идей. Я попытался переустановить C ++, возиться с:

using namepace std;
using std::string;
std::string instead of string
etc.

Если вы знаете, как решить мою проблему, я хотел бы услышать от вас. Я более чем рад предоставить больше информации.

-3

Решение

C ++ выполняет однопроходную компиляцию, поэтому std :: string необходимо объявить перед тем, как использовать его вообще — в том числе в заголовочном файле.

// Temp.h
#pragma once

#include <string>

class Temp
{
public:
Temp();

void doSomething(std::string blah);
};

Я бы посоветовал вам быть более точным в ваших заголовочных файлах при указании таких классов, потому что вы можете легко встретить другую библиотеку, которая определяет свою собственную string и тогда вы столкнетесь с конфликтами имен. Спасти using импортировать операторы для ваших файлов cpp.

0

Другие решения

У πάντα ῥεῖ был письменный ответ, спасибо!

Они сказали использовать std :: string при необходимости, а также #include <string> в заголовочном файле.

0

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка ккт 3933
  • Ошибка кислородного датчика шевроле круз
  • Ошибка контрольной суммы cmos что делать
  • Ошибка компилятора c2040
  • Ошибка клапана егр гольф 4

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: