What’s wrong with this line of code?
bar foo(vector ftw);
It produces
error C2061: syntax error: identifier 'vector'
bdonlan
223k30 gold badges266 silver badges323 bronze badges
asked Jun 11, 2010 at 22:04
Nick HeinerNick Heiner
118k187 gold badges474 silver badges698 bronze badges
try std::vector instead. Also, make sure you
#include <vector>
answered Jun 11, 2010 at 22:06
Adrian GrigoreAdrian Grigore
33k36 gold badges130 silver badges210 bronze badges
Probably you forgot to include vector and/or import std::vector
into the namespace.
Make sure you have:
#include <vector>
Then add:
using std::vector;
or just use:
bar foo(std::vector<odp> ftw);
answered Jun 11, 2010 at 22:06
Matthew FlaschenMatthew Flaschen
277k50 gold badges513 silver badges538 bronze badges
1
Do you have:
#include <vector>
and
using namespace std;
in your code?
<vector>
defines the std::vector
class, so you need to include it some where in your file.
since you’re using vector
, you need to instruct the compiler that you’re going to import the whole std
namespace (arguably this is not something you want to do), via using namespace std;
Otherwise vector should be defined as std::vector<myclass>
answered Jun 11, 2010 at 22:06
try std::vector<odp>
or using std;
answered Jun 11, 2010 at 22:06
TreDubZeddTreDubZedd
2,5511 gold badge15 silver badges20 bronze badges
On its own, that snippet of code has no definition of bar
, vector
or odp
. As to why you’re not getting an error about the definition of bar
, I can only assume that you’ve taken it out of context.
I assume that it is supposed to define foo
as a function, that vector
names a template and that it is supposed to define a parameter called ftw
but in a declaration anything that is not actually being defined needs to have been declared previously so that the compiler knows what all the other identifiers mean.
For example, if you define new types as follows you get a snippet that will compile:
struct bar {};
struct odp {};
template<class T> struct vector {};
bar foo(vector<odp> ftw);
answered Jun 11, 2010 at 22:07
CB BaileyCB Bailey
746k102 gold badges631 silver badges655 bronze badges
Синтаксическая ошибка: идентификатор «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 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. Показов 17698. Ответов 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 |
Rishka 0 / 0 / 0 Регистрация: 16.03.2013 Сообщений: 13 |
||||
1 |
||||
21.01.2016, 17:01. Показов 3854. Ответов 3 Метки нет (Все метки)
Выдаёт ошибку error C2061: синтаксическая ошибка: идентификатор «String». В чём причина не знаю. Помогите, пожалуйста.
__________________ 0 |
skaa Хочу в Исландию 1041 / 840 / 119 Регистрация: 10.11.2010 Сообщений: 1,630 |
||||
21.01.2016, 18:44 |
2 |
|||
Может быть это поможет: в VS 2008 надо типа так:
1 |
Администратор 15226 / 12265 / 4902 Регистрация: 17.03.2014 Сообщений: 24,867 Записей в блоге: 1 |
|
21.01.2016, 18:59 |
3 |
Rishka, String^ это .NET-й тип. Для него нужен 1 |
IGPIGP Комп_Оратор) 8771 / 4510 / 608 Регистрация: 04.12.2011 Сообщений: 13,454 Записей в блоге: 16 |
||||
21.01.2016, 20:33 |
4 |
|||
если даже не «lalala» тогда точно ноль. 0 |
Вопрос:
это, вероятно, проблема включения, я получаю эти ошибки по всему коду, а не только для идентификатора строки, например error C2146: syntax error : missing ';' before identifier 'getName'
и error C2146: syntax error : missing ';' before identifier 'name'
здесь пример класса:
#include "stdafx.h"
class participant
{
public:
participant(int id, string name);
~participant(void);
int getId();
string getName();
private:
int id;
string name;
};
вот мой stdafx.h
файл:
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <list>
#include "day.h"
#include "appointment.h"
#include "extendedAppointment.h"
#include "participant.h"
#include "calendar.h"
using namespace std;
#define no_such_appointment_error 20;
#define conflicting_appointments_error 21;
#define noSuchDayError 22;
#define incorrectAppointmentError 23;
Лучший ответ:
Итак, я скомпилировал ваш код как опубликованный без ваших пользовательских файлов заголовков, и он работал нормально. Исходя из этого, я собираюсь заявить, что у вас есть проблема в одном из этих файлов заголовков:
#include "day.h"
#include "appointment.h"
#include "extendedAppointment.h"
#include "participant.h"
#include "calendar.h"
Это может быть макрос, класс/структура не оканчивается точкой с запятой и т.д. Проверьте их.
Наконец, несколько тангенциальных проблем:
Во-первых, using
пространство имен в файле заголовка – ужасная идея. Любой файл, который содержит ваш заголовок, теперь имеет using namespace std;
в нем (это плохо). Вероятно, вы не хотите включать в него много файлов заголовков, в которые входит stdafx.h
.
Во-вторых, после удаления, тогда string
сразу становится undefined (вместо этого используйте std::string).
Наконец, почему ваш #define
закончился полуколонами? Нет необходимости в этом.
- Forum
- Beginners
- syntax error identifier string.
syntax error identifier string.
Hi,
I’m getting an error C2061: syntax error : identifier ‘string’. Could you help me please?
|
|
|
|
|
|
thanks in advance for your help
|
|
I noticed I forgot namespace std; but it still has the error
Last edited on
I get about 500 errors from this project. Oh well maybe it was setup wrong. and its actually 81 errors
Last edited on
Topic archived. No new replies allowed.
Содержание
- Syntax error identifier что это
- ошибка C2061: синтаксическая ошибка: идентификатор, но заголовочный файл уже включен
- Решение
- Syntax error identifier что это
- Answered by:
- Question
- Answers
- Syntax error identifier что это
- Answered by:
- Question
- Answers
- All replies
- Syntax error identifier что это
Syntax error identifier что это
Hey guys, I’m am still a semi beginner at C++ programming. I have this issue with an syntax error identifier that I just cannot see any reason for no matter how hard I look. If anyone could help it would be much appreciated.
Here are the classes involved:
If you need any other parts of the code please let me know. thanks!
this error:
c:usersuserdocumentsvisual studio 2012projectsthe best rpgthe best rpgmain.cpp(215): error C2660: ‘Direct3D::Draw’ : function does not take 2 arguments
1> ThirdPersonCamera.cpp
is in the main.cpp file. So is the one above it.
for ( unsigned int i = 0; i
what type does entities.size() return?
if it returns int, you should have
for ( int i = 0; i
Thanks for your replies. the errors in the main.cpp are being caused by the syntax error : idenifier because that Draw function takes in a ThirdPersonCamera, what I need to deal with is the identifier errors, i tested removing the include you mentioned but it is required.
It is required for the DirectX stuff. The reason why I mention this is because if you have a circular dependency the compiler will generate unknown identifier errors because it does not know how to build your object.
Consider removing your directx header and replace in its stead the dirextx includes required to make your thirdpersoncamera class work.
Источник
У меня есть большой движок для компиляции, и он работал нормально, пока я не сделал некоторые сумасшедшие настройки. Компилятор так или иначе не может преобразовать мой средний объект Game и произвести error C2061: syntax error : identifier ‘Game’ и кажется, что независимо от того, какой файл я компилирую, ошибка всегда указывает на файл с именем GameDataLoader.h даже нет абсолютно никакой связи с этими двумя файлами. Обычно я думаю, что это проблема включения, но на самом деле у меня есть Game.h включается в каждый необходимый файл .h, сразу после включения stdafx.h и у меня #pragama once на нем. Я думал о проблеме кругового включения, но #pragma once должен позаботиться об этом. Плюс это директивы включения работает нормально, пока я не изменил имя файла и другие грязные вещи. Я очистил все решение и попытался восстановить его, но все равно не повезло (используя VS2012).
Я не знаю, поможет ли показ кода, но вот код для gameDataLoader.h , Это не файл, который я написал, но он должен работать правильно.
И у меня были ошибки именно на этих 4 строках с объектом Game. В чем может быть проблема?
Двойное включение? Круговое включение? Или не включили что-то и где-то еще?
Решение
Более вероятный, Game.h в том числе GameDataLoader.h прямо или косвенно, создавая круговую зависимость; но ты забыл показать нам Game.h Так что я не могу быть уверен в этом.
Если это так, то #pragma once (или эквивалентное включение защиты) будет означать, что один из заголовков будет включен раньше другого, а объявления второго не будут доступны первому. Он не будет волшебным образом включать их обоих друг перед другом, поскольку это невозможно.
К счастью, GameDataLoader.h не нужно полное определение Game , поскольку он имеет дело только с указателями на него. Таким образом, вы можете удалить включение Game.h и просто объявить class Game; вместо.
Источник
Syntax error identifier что это
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I am migrating my application frm vc++6.0 to vc++2008,
I am facing one more error in the same line : error C2310: catch handlers must specify one type
I am sending the part of code were iam facing the error by highlighting the error line.
try <
m_oFileStream.open(OLE2CT(m_szFileName));
>
catch (exception& ) < //error line
return this->Error(IDS_ERR_IOEXCEPTION, IID_ITextFileParser, E_FAIL);
>
if (m_oFileStream.fail())
return this->Error(IDS_ERR_NOFILE, IID_ITextFileParser, E_FAIL);
CComBSTR szHelpSep(szSep);
if (szHelpSep.Length() > 0)
m_cSeparator = OLE2CT(szHelpSep)[0];
else
m_cSeparator = ‘’;
can anyone suggest me the solution for this
Answers
On 2/6/2014 4:06 AM, SimonRev wrote:
It shouldn’t matter whether you catch exception& or exception, the catch handler will be invoked. Normally you would handle by reference though, as that will prevent extra copies of the exception object being made.
You absolutely want to catch exception&. std::exception is a base class for a large hierarchy of exception classes; normally, you would expect some derived class to be thrown, not std::exception itself. If you catch by value, the object will be sliced — you are going to lose all extra information in the derived class (in particular, virtual what() method will be called on the wrong class). Catching by reference is the only sane course of action.
It shouldn’t matter whether you catch exception& or exception, the catch handler will be invoked. Normally you would handle by reference though, as that will prevent extra copies of the exception object being made.
Источник
Syntax error identifier что это
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I have an mfc program that I am making in .net 2.0 and im referencing system.dll for the tcp socket namespace.
#using
[code]
System: tring ^sip=gcnew System: tring(ip);
System::UInt16 ^sport = gcnew System::UInt16(port);
System: tring ^sdata = gcnew System: tring(data);
//error on this line. ‘‘ error
System::Net: ockets::TcpClient ^tcp = gcnew ///////this and next line are all 1 line
System::Net: ockets::TcpClient::TcpClient(sip,System::Convert::ToInt32(sport));
[/code]
What is wrong with this line of code? why am I getting a ctor error and what does that even mean?
Thanks
Answers
You dont have to access the constructor directly (TcpClient::TcpClient) ,
System::String ^sip=gcnew System::String(ip);
System::UInt16 ^sport = gcnew System::UInt16(port);
System::String ^sdata = gcnew System::String(data);
//error on this line. ‘‘ error
System::Net::Sockets::TcpClient ^tcp = gcnew
System::Net::Sockets::TcpClient(sip,System::Convert::ToInt32(sport));
abcdefgqwerty2 wrote: | ||||||||||||||||||||||||||||||||||||||||||||||||||
I just dont understand why. Shouldnt I be able to use the constructor? I was doing this and using the system:tring constructor so it seems I could also use the tcpclient constructor. Imagine doing int* c = new int::int, or ref class MyClass <>; MyClass^ p = gcnew MyClass::MyClass(). You’re allocating an instance of the type, not the constructor, hence you shouldn’t (and cannot) pass the constructor. All repliesYou dont have to access the constructor directly (TcpClient::TcpClient) , System::String ^sip=gcnew System::String(ip); //error on this line. ‘‘ error
You’re passing the constructor to gcnew, rather than the type. I see. The line works as this System::Net: ockets::TcpClient ^tcp =gcnew System::Net: ockets::TcpClient; I just dont understand why. Shouldnt I be able to use the constructor? I was doing this and using the system: tring constructor so it seems I could also use the tcpclient constructor. bool SendString(const char *ip,unsigned short port,char *data,char *outdata) Источник Syntax error identifier что этоЭто основывается на предыдущее мое сообщение, но поскольку тема другая я вывел это в отдельную ветку. Error 1 error C2061: syntax error : identifier ‘ElementType’
Здравствуйте, TheAteist, Вы писали: Во-первых (из другого топика): Во-вторых (взято из уже удалённого сообщения): TA>Вот часть другого кода(приведен ниже) на который компайлер тоже кричит Вот почему (см. выделенное): Нужно разорвать циклическую зависимость. Лучше, переработав заголовки.
Здравствуйте, Alexey F, Вы писали: AF>Во-вторых (взято из уже удалённого сообщения): Что я уже только не пробывал, чтоб это исправить эту циклическую зависимость. должен быть в customer.h, т.к. он к нему относится Как можно исправить? AF>Вот почему (см. выделенное): AF>Нужно разорвать циклическую зависимость. Лучше, переработав заголовки.
Кажется я нашел решение только не знаю почему так работает и правильно ли и в файле «customer.h» я поменял
Здравствуйте, TheAteist, Вы писали: TA>Маленькая поправка, List L не должен хранится в AssetDetails. Так это совершенно другое дело!
и в файле «customer.h» я поменял
Здравствуйте, Alexey F, Вы писали: ошибка была потому-что уже имелось «typedef struct. » в «customer.h», а я добавил еше раз «typedef Demand ElementType» в «list.h»? как эта ошибка называется? Огромное вам спасибо за помошь.
Здравствуйте, TheAteist, Вы писали: TA>ошибка была потому-что уже имелось «typedef struct. » в «customer.h», а я добавил еше раз «typedef Demand ElementType» в «list.h»? как эта ошибка называется?
Он не знал, что Demand — это структура. «struct Demand;» или «typedef struct Demand ElementType;» дали ему такую подсказку. TA>и почему хотя у меня имеется «#define NAME_LEN 20» который НЕ в #ifndef и подключается в нескольких файлах, то не происходит ошибки? P.S. Как осободитесь, рекомендую Вам более детально просмотреть где-нибудь информацию про внутреннее/внешнее связывание и предварительные объявления структур. Источник |