Синтаксическая ошибка: идентификатор «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();
};
|
aprkaer 0 / 0 / 0 Регистрация: 05.12.2012 Сообщений: 9 |
||||
|
1 |
||||
|
19.05.2013, 12:44. Показов 17840. Ответов 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 |
|
Неэпический 17848 / 10616 / 2049 Регистрация: 27.09.2012 Сообщений: 26,686 Записей в блоге: 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

