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
2881 gold badge6 silver badges18 bronze badges
asked Apr 3, 2013 at 8:32
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
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 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
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 
- 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:
- I use
#pragma oncein every header - 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».
0 |
|
5496 / 4891 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
|
19.05.2013, 12:56 |
2 |
|
что с этим делать? Заменить на 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 минут
0 |
|
Issues 433 / 368 / 149 Регистрация: 06.08.2012 Сообщений: 961 |
||||
|
19.05.2013, 14:34 |
5 |
|||
|
int main(int argc, _TCHAR* argv[]) может просто написать?
0 |
|
alsav22 5496 / 4891 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
||||
|
19.05.2013, 14:37 |
6 |
|||
|
может просто написать?
Я так понял, что ТС нужно использовать _TCHAR.
0 |
|
Issues 433 / 368 / 149 Регистрация: 06.08.2012 Сообщений: 961 |
||||
|
19.05.2013, 14:42 |
7 |
|||
|
Я так понял, что ТС нужно использовать _TCHAR. но ведь он как и
в программе нигде не используется.
0 |
|
Croessmah |
||||
|
19.05.2013, 14:43
#8 |
||||
|
Не по теме: alsav22, не думаю что ему нужен TCHAR:
0 |
|
alsav22 |
|
19.05.2013, 14:50
|
|
Не по теме: Тогда я не понимаю его третий пост.
0 |
|
Issues |
|
19.05.2013, 14:54
|
|
Не по теме:
Тогда я не понимаю его третий пост. скорее всего он вставляет этот код в простой «Win32 Console Application»
0 |
|
alsav22 |
|
19.05.2013, 14:59
|
|
Не по теме:
Не по теме: скорее всего он вставляет этот код в простой «Win32 Console Application» И что, в нём нельзя заменить _TCHAR на char?
0 |
|
Issues |
|
19.05.2013, 15:02
|
|
Не по теме:
И что, в нём нельзя заменить _TCHAR на char? можно.
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 |
|
Не по теме:
Да что мы гадаем…нам за это не платят — зайдет пояснит Пояснил, называется…
и добавление #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 |
|
TCAR на char не канает, ошибки Ошибки какие?
0 |
|
0 / 0 / 0 Регистрация: 05.12.2012 Сообщений: 9 |
|
|
20.05.2013, 00:27 [ТС] |
19 |
|
error C2061: синтаксическая ошибка: идентификатор «_TCHAR» Добавлено через 1 минуту
0 |
|
5496 / 4891 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
|
20.05.2013, 01:07 |
20 |
|
error C2061: синтаксическая ошибка: идентификатор «_TCHAR» Если заменить _TCAR на char? Откуда там такая ошибка может взяться, если _TCHAR уже нет? Добавлено через 12 минут 1>—— Построение начато: проект: CLR3Cons, Конфигурация: Debug Win32 —— Не находит реализацию для CharToOemA()? Добавлено через 7 минут
Пришли пожалуйста 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

