this is probably an include problem, i get these errors all over the code, and not only for string identifier for example error C2146: syntax error : missing ';' before identifier 'getName'
and error C2146: syntax error : missing ';' before identifier 'name'
here’s an example class:
#include "stdafx.h"
class participant
{
public:
participant(int id, string name);
~participant(void);
int getId();
string getName();
private:
int id;
string name;
};
here’s my stdafx.h
file:
#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;
asked May 14, 2012 at 18:53
10
So I compiled your code as-posted without your custom header files and it worked just fine. Based on that, I am going to wager that you have a problem in one of these header files:
#include "day.h"
#include "appointment.h"
#include "extendedAppointment.h"
#include "participant.h"
#include "calendar.h"
It could be a macro, a class/struct not terminated with a semi-colon, etc. Check those out.
Lastly, a few of tangential issues:
First, using
a namespace in a header file is a terrible idea. Any file that includes your header now has using namespace std;
in it (this is bad). You probably don’t want to include that many header files in every file that includes stdafx.h
.
Secondly, once you remove that then string
immediately becomes undefined (use std::string instead).
Last, why are your #define
s ended with semi-colons? No need for that.
answered May 14, 2012 at 19:01
Ed S.Ed S.
122k22 gold badges182 silver badges263 bronze badges
6
Rishka 0 / 0 / 0 Регистрация: 16.03.2013 Сообщений: 13 |
||||
1 |
||||
21.01.2016, 17:01. Показов 4260. Ответов 3 Метки нет (Все метки)
Выдаёт ошибку error C2061: синтаксическая ошибка: идентификатор «String». В чём причина не знаю. Помогите, пожалуйста.
0 |
skaa Хочу в Исландию 1041 / 840 / 119 Регистрация: 10.11.2010 Сообщений: 1,630 |
||||
21.01.2016, 18:44 |
2 |
|||
Может быть это поможет: в VS 2008 надо типа так:
1 |
Администратор 15668 / 12629 / 5003 Регистрация: 17.03.2014 Сообщений: 25,708 Записей в блоге: 1 |
|
21.01.2016, 18:59 |
3 |
Rishka, String^ это .NET-й тип. Для него нужен
1 |
IGPIGP Комп_Оратор) 8863 / 4602 / 621 Регистрация: 04.12.2011 Сообщений: 13,740 Записей в блоге: 16 |
||||
21.01.2016, 20:33 |
4 |
|||
если даже не «lalala» тогда точно ноль.
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
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. Как осободитесь, рекомендую Вам более детально просмотреть где-нибудь информацию про внутреннее/внешнее связывание и предварительные объявления структур. Источник |
- 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.