Error c2061 синтаксическая ошибка идентификатор

When I compile there is an error call «error C2061: syntax error : identifier ‘Player’ «

I can’t figure out what is wrong with my code. Here is my code

#include "Platform.h"
#include "Player.h"
class Collision
{
public:
  Collision(void);
  ~Collision(void);
  static bool IsCollision(Player &player, Platform& platform);
};

There is an error in «IsCollision» method.

Player.h

#include <SFML/Graphics.hpp>
#include "rapidxml.hpp"
#include <fstream>
#include <iostream>
#include "Collision.h"
using namespace rapidxml;
class Player
{
private:
    sf::Texture playerTexture;
    sf::Sprite playerSprite;
    sf::Vector2u position;
    sf::Vector2u source;
    sf::Vector2u size;
    int frameCounter, switchFrame, frameSpeed;
    int walkSpriteWidth;
    float velocity;
    bool isWalk;
    bool isStand;
    bool isFaceRight;

public:
    Player(void);
    ~Player(void);

    void Init();
    void Draw(sf::RenderWindow *window);
    void MoveForward();
    void MoveBackward();
    void Update(sf::Clock *clock);
    void SetSourceY(int value);
    void SetWalk(bool value);
    void SetFacing(std::string value);
    void SetStand(bool value);
    void Stand();
    std::string GetStatus();
    void PrintStatus();
    sf::Vector2f GetPosition();
    int GetWidth();
    int GetHeight();
};

georges619's user avatar

georges619

2881 gold badge6 silver badges18 bronze badges

asked Apr 3, 2013 at 8:32

aratn0n's user avatar

7

You have a circular include dependency. Collision.h includes Player.h and vice versa. The simplest solution is to remove #include "Collision.h" from Player.h, since the Collision class is not needed in the Player declaration. Besides that, it looks like some of your includes in Collision.h can be replaced by forward declarations:

// forward declarations
class Player;
class Platform;

class Collision
{
public:
  Collision(void);
  ~Collision(void);
  static bool IsCollision(Player &player, Platform& platform);
};

You can then put the includes in Collision‘s implementation file.

answered Apr 3, 2013 at 8:37

juanchopanza's user avatar

juanchopanzajuanchopanza

222k33 gold badges399 silver badges479 bronze badges

0

That’s a pretty common mistake — you have circular include dependency.

Looking at your code, you should replace #include "Player.h" with class Player; in Collision.h. This is called «forward declaration» and will break the circular dependency.


Also, it would be good to add include guards, for example:

#ifndef MY_PLAYER_CLASS
#define MY_PLAYER_CLASS

...

#endif

And this should be done for each header you write.

answered Apr 3, 2013 at 8:37

Kiril Kirov's user avatar

Kiril KirovKiril Kirov

37.3k22 gold badges112 silver badges187 bronze badges

Circular dependency or you’re using a C compiler for C++ code

answered Apr 8, 2019 at 16:09

Stocazzo's user avatar

1

Синтаксическая ошибка: идентификатор «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);
};

QUESTION (answer below the question)

I know there’s lot of questions like mine, but I didn’t find the solution for my problem anyway.

I’w writing small project for school and everything was running with no problem until I added: #include "robot.h" into interface.h and added , Robot* _robot in init function in interface.h.

I’m writing it with Visual Studio 2013 Ultimate (I’m a student ;) ). The whole code is accessible on github and those are files written by me:

  • allegroHelper.h .cpp — some functions for ease of use allegro library
  • interface.h .cpp — class for drawing interface
  • logic.h .cpp — logic of the robot
  • robot.h .cpp — robot class
  • libs/xkontiTextUtils.h .cpp — some fancy console functions (some are broken)
  • libs/xkontiVector2d.h .cpp — little vector class

The thing that is breaking my code is there:

//interface.h
#pragma once


//////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////

#include <string>
#include <vector>
#include "libs/xkontiTextUtils.h"
#include "libs/xkontiVector2d.h"
#include <allegro5/allegro.h>
#include "allegro5/allegro_image.h"
#include <allegro5/allegro_primitives.h>
#include "robot.h"
//#include "allegroHelper.h"    // Not needed due to forward declatation?


//////////////////////////////////////////
// INTERFACE CLASS
//////////////////////////////////////////

class Interface {
public:
    Interface();
    ~Interface();

    bool init(std::string _mapPath, int _width, XkontiConsoleColors* _con, Robot* _robot);
    (...)
    Robot* robot;
    (...)
};

Robot class is in robot.h:

//robot.h
#pragma once


//////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////

#include <iostream>

#include <vector>
#include <math.h>
#include "libs/xkontiTextUtils.h"
#include "libs/xkontiVector2d.h"

#include <allegro5/allegro.h>
#include "allegro5/allegro_image.h"
#include <allegro5/allegro_primitives.h>

#include "allegroHelper.h"


//////////////////////////////////////////
// ROBOT CLASS
//////////////////////////////////////////

class Robot {
public:
    // Constuctor & Destructor
    Robot(std::vector< std::vector<bool> >& _map);
    ~Robot();

    // Initialization functions
    void initBody(Vector2D _size, Vector2D _pos, double _rotation, double _maxVelocity, double _maxAVelocity);
    void initHead(Vector2D _pos, Vector2D _rotRange, double _rangeMin, double _rangeMax, double _rangeError, unsigned int _resolution, double _rangeLess, double _rangeOver);

    // Set Functions
    void setPos(Vector2D _newPos);
    void setPos(double _x, double _y);
    void setRotation(double _rad);

    // Get Functions
    Vector2D getPos();
    Vector2D getHeadPos();
    double getRotation();
    int getStatus();

    // Commands Functions
    void move(double _dist);                // Move robot forward by specified distance
    void move(double _dist, double _rad);   // Move and turn robot
    void turn(double _rad);             // Turn robot by specified degree value
    std::vector<double>& scan();        // Scans terrain. Returns reference to vector of distances.

    // Periodical Functions
    void update(double dt);
    void draw(double dt);

    // Public Variables
    std::vector<Vector2D> scanPoints;

private:
    // Body functions

    // Head functions
    double trace(double _rad);          // Measure distance from current position

    // Outside pointers
    std::vector< std::vector<bool> >& map;

    // Body properties
    Vector2D size;      // Dimensions: Width, Length
    Vector2D pos;           // Position: X, Y
    double rotation;                    // Rotation: Z axis
    double leftDistance;                // Distance left to travel
    double leftRotation;                // Rotation left to rotate
    double maxVelocity;             // Max forward velocity
    double maxAVelocity;                // Max angular velocity on Z axis (left/right)

    // Head properties
    Vector2D headPos;           // Head position: X, Y
    Vector2D headRotRange;  // Head Z rotation range: from - to in deg
    double rangeMin;            // Minimum and Maximum detection range
    double rangeMax;
    double rangeError;          // Error percentage on range measuring
    unsigned int resolution;    // Number of traces in left/right scan
    double rangeLess;           // Number used when something was nearer than rangeMin
    double rangeOver;           // Number used when nothing was detected
};

The error I’m getting from compiler:

1>------ Build started: Project: RoboSim, Configuration: Debug Win32 ------
1>  robot.cpp
1>d:xkontigithubrobosiminterface.h(28): error C2061: syntax error : identifier 'Robot'
1>d:xkontigithubrobosiminterface.h(39): error C2143: syntax error : missing ';' before '*'
1>d:xkontigithubrobosiminterface.h(39): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>  logic.cpp
1>d:xkontigithubrobosiminterface.h(28): error C2061: syntax error : identifier 'Robot'
1>d:xkontigithubrobosiminterface.h(39): error C2143: syntax error : missing ';' before '*'
1>d:xkontigithubrobosiminterface.h(39): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>  xkontiVector2d.cpp
1>  Generating Code...
1>  Skipping... (no relevant changes detected)
1>  interface.cpp
1>  allegroHelper.cpp
1>  RoboSim.cpp
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I looked for circular dependencies with #include but:

  1. I use #pragma once in every header
  2. I found that I include interface.h in allegroHelper.h and allegroHelper.h in interface.h and it was compiling without problem for long time.

Can you tell me what am I doing wrong? Or any hints what to check?

ANSWER

Ok. I dont have much time and because I didn’t find any way to have pointer to Robot class in Interface, I’m accessing data by references to some data in Robot class.

In main file:

//RoboSim.cpp
std::vector< std::vector<bool> > map;
std::vector<Vector2D> scanPoints;
ALLEGRO_BITMAP* image = nullptr;
(...)
Interface inter = Interface(scanPoints);
Robot robot = Robot(map, scanPoints);
(...)

In Interface class:

//interface.h
(...)
class Interface {
public:
    Interface(std::vector<Vector2D>& _scanPoints);
    ~Interface();
    (...)
private:
    XkontiConsoleColors* con;
    std::vector<Vector2D>& scanPoints;
    (...)

In Robot class:

//robot.h
(...)
class Robot {
public:
    // Constuctor & Destructor
    Robot(std::vector< std::vector<bool> >& _map, std::vector<Vector2D>& scanPoints);
    ~Robot();
    (...)
    std::vector< std::vector<bool> >& map;
    std::vector<Vector2D>& scanPoints;
    (...)

aprkaer

0 / 0 / 0

Регистрация: 05.12.2012

Сообщений: 9

1

19.05.2013, 12:44. Показов 17696. Ответов 19

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Программа по обходу в глубину графа. вылетает error C2061: синтаксическая ошибка: идентификатор «_TCHAR».
что с этим делать?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 2w3.cpp: главный файл проекта.
 
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <string>
#include <windows.h>
using namespace System;
using namespace std;
 
vector<vector<int>> Mat;
vector<int> Vec;
vector<char> used;
void dfs (int v) {
    used[v] = true;
    for (int i=0; Mat.size(); ++i)
        if (!used[i])
            dfs (i);
}
 
/////////////////////////Функция русификации////////////////////////////
char *Rus(char *ps){
    char *buf=new char[strlen(ps)];
    CharToOemA(ps,buf);
    return buf;
}
int main(int argc, _TCHAR* argv[]){
 
    cout<<Rus("Введите количество вершин:");
    int nCount,i=0;
    cin>>nCount;
    while(i!=nCount){
        cout<<Rus("Введите строку списка, если захотите закончить ввод нажмите -1:")<<endl;
        int op;
        for(int j=0;;++j){
            cin>>op;
            if(op!=-1){Vec.push_back(op);}
            else {break;}
        }
        Mat.push_back(Vec);
        Vec.clear();
        ++i;
    }
    cout<<Rus("Введите вершину, с которой вы хотите построить пвг:");
    int v;
    cin>>v;
    dfs(v);
    
    return 0;
}



0



5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

19.05.2013, 12:56

2

Цитата
Сообщение от aprkaer
Посмотреть сообщение

что с этим делать?

Заменить на char.



0



0 / 0 / 0

Регистрация: 05.12.2012

Сообщений: 9

19.05.2013, 14:19

 [ТС]

3

ха-ха. если б всё так просто.



0



alsav22

5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

19.05.2013, 14:29

4

Какой вопрос — такой и ответ. Вставляю ваш код в студию, заменяю, и компиляция без ошибок.

Добавлено через 6 минут
Ещё вариант:

C++
1
#include <tchar.h>



0



Issues

433 / 368 / 149

Регистрация: 06.08.2012

Сообщений: 961

19.05.2013, 14:34

5

Цитата
Сообщение от aprkaer
Посмотреть сообщение

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

может просто написать?

C++
1
int main()



0



alsav22

5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

19.05.2013, 14:37

6

Цитата
Сообщение от SeregaC++
Посмотреть сообщение

может просто написать?

C++
1
int main()

Я так понял, что ТС нужно использовать _TCHAR.



0



Issues

433 / 368 / 149

Регистрация: 06.08.2012

Сообщений: 961

19.05.2013, 14:42

7

Цитата
Сообщение от alsav22
Посмотреть сообщение

Я так понял, что ТС нужно использовать _TCHAR.

но ведь он как и

C++
1
using namespace System;

в программе нигде не используется.



0



Croessmah

19.05.2013, 14:43

 

#8

Не по теме:

alsav22, не думаю что ему нужен TCHAR:

C++
1
2
3
4
5
char *Rus(char *ps){
    char *buf=new char[strlen(ps)];
    CharToOemA(ps,buf);
    return buf;
}



0



alsav22

19.05.2013, 14:50

Не по теме:

Тогда я не понимаю его третий пост.



0



Issues

19.05.2013, 14:54

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

Тогда я не понимаю его третий пост.

скорее всего он вставляет этот код в простой «Win32 Console Application»



0



alsav22

19.05.2013, 14:59

Не по теме:

Цитата
Сообщение от SeregaC++
Посмотреть сообщение

Не по теме:

скорее всего он вставляет этот код в простой «Win32 Console Application»

И что, в нём нельзя заменить _TCHAR на char?



0



Issues

19.05.2013, 15:02

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

И что, в нём нельзя заменить _TCHAR на char?

можно. :D



0



Croessmah

19.05.2013, 15:04

Не по теме:

Да что мы гадаем…нам за это не платят — зайдет пояснит :)



0



0 / 0 / 0

Регистрация: 05.12.2012

Сообщений: 9

19.05.2013, 21:32

 [ТС]

14

TCAR на char не канает, оибки и добавление #include char тоже.



0



5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

19.05.2013, 23:34

15

Не по теме:

Цитата
Сообщение от Croessmah
Посмотреть сообщение

Да что мы гадаем…нам за это не платят — зайдет пояснит

Пояснил, называется…

Цитата
Сообщение от aprkaer
Посмотреть сообщение

и добавление #include char тоже

А #include <tchar.h> ? Что за среда? Проект?



0



0 / 0 / 0

Регистрация: 05.12.2012

Сообщений: 9

19.05.2013, 23:59

 [ТС]

16

CLR console application/ visual studio 2010



0



Неэпический

17815 / 10586 / 2044

Регистрация: 27.09.2012

Сообщений: 26,627

Записей в блоге: 1

20.05.2013, 00:12

17

C++ и C++/CLI разные языки.



0



5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

20.05.2013, 00:13

18

Цитата
Сообщение от aprkaer
Посмотреть сообщение

TCAR на char не канает, ошибки

Ошибки какие?



0



0 / 0 / 0

Регистрация: 05.12.2012

Сообщений: 9

20.05.2013, 00:27

 [ТС]

19

error C2061: синтаксическая ошибка: идентификатор «_TCHAR»

Добавлено через 1 минуту
Пришли пожалуйста EXE-шник, если компилится. zelenyy81@mail.ru



0



5496 / 4891 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

20.05.2013, 01:07

20

Цитата
Сообщение от aprkaer
Посмотреть сообщение

error C2061: синтаксическая ошибка: идентификатор «_TCHAR»

Если заменить _TCAR на char? Откуда там такая ошибка может взяться, если _TCHAR уже нет?

Добавлено через 12 минут
Ошибки там другие появляются, компоновщик выдаёт:

1>—— Построение начато: проект: CLR3Cons, Конфигурация: Debug Win32 ——
1> CLR3Cons.cpp
1>CLR3Cons.obj : error LNK2028: ссылка на неразрешенную лексему (0A000408) «extern «C» int __stdcall CharToOemA(char const *,char *)» (?CharToOemA@@$$J18YGHPBDPAD@Z) в функции «extern «C» char * __cdecl Rus(char const *)» (?Rus@@$$J0YAPADPBD@Z)
1>CLR3Cons.obj : error LNK2019: ссылка на неразрешенный внешний символ «extern «C» int __stdcall CharToOemA(char const *,char *)» (?CharToOemA@@$$J18YGHPBDPAD@Z) в функции «extern «C» char * __cdecl Rus(char const *)» (?Rus@@$$J0YAPADPBD@Z)
1>D:MY C++ProjectsCLR3ConsDebugCLR3Cons.exe : fatal error LNK1120: 2 неразрешенных внешних элементов
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

Не находит реализацию для CharToOemA()?

Добавлено через 7 минут

Цитата
Сообщение от aprkaer
Посмотреть сообщение

Пришли пожалуйста EXE-шник, если компилится.

Тут всё дело в пректе. Компилится без проблем, если проект не CLR.



0



Я пытаюсь изучать 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

Понравилась статья? Поделить с друзьями:
  • Error c2059 синтаксическая ошибка строка
  • Error c2059 синтаксическая ошибка константа
  • Error 80004005 неопознанная ошибка elsa что делать
  • Error 8 кофемашина jura как исправить ошибку
  • Error 601 battery как убрать ошибку