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

Я пытаюсь изучать 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. Показов 4337. Ответов 3

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


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

Выдаёт ошибку error C2061: синтаксическая ошибка: идентификатор «String». В чём причина не знаю. Помогите, пожалуйста.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>
#include <iostream> 
using namespace std;
 
 
class Factory {
public: int createObez(String^ kind){
        if (kind == "Широконосый") 
             {Shirikonosiy* sh = new Shirikonosiy(); return sh->nomkar;}
             else 
                 if (kind == "Узконосый") 
                 {Uzkonosiy *uz = new Uzkonosiy(); return uz->nomkar;}
                 else 
                     if (kind == "Человекообразный") 
                     {Chelovekoobrazniy* ch = new Chelovekoobrazniy(); return ch->nomkar;}
        }
};



0



skaa

Хочу в Исландию

1041 / 840 / 119

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

Сообщений: 1,630

21.01.2016, 18:44

2

Может быть это поможет: в VS 2008 надо типа так:

C++
1
2
3
4
5
6
7
8
9
    class Factory
    {
        public int createObez(String kind)
        {
            if (kind == "lalala")
                return 1;
            return 0;
        }
    }



1



Администратор

Эксперт .NET

16314 / 12805 / 5058

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

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

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

21.01.2016, 18:59

3

Rishka, String^ это .NET-й тип. Для него нужен using namespace System; и проект с поддержкой CLR. Ты точно пишешь на управляемом C++? Если нет, то тогда используй родные C++ типы. Например, std::string.



1



IGPIGP

Комп_Оратор)

Эксперт по математике/физике

8916 / 4677 / 626

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

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

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

21.01.2016, 20:33

4

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

C++
1
kind == "lalala" ...return 1;...else return 0;

если даже не «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?

1
2
3
4
5
6
7
8
class Person
{
public:
	Person(string stName);
	virtual void Print() const;
private:
	string m_stName;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include "Person.h"

Person::Person(string stName)
:m_stName(stName)
{
	//Empty
}
void Person::Print() const
{
	cout << "Name: " << m_stName << endl;
}
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
#include <iostream>
#include "Person.h"
#include "Student.h"
#include "Employee.h"

using namespace std;

void main()
{
	Person person("John Smith");
	person.Print();
	cout << endl;
	Student student("Mark Jones", "MIT");
	student.Print();
	cout << endl;
	Employee emloyee("Adam Brown", "Microsoft");
	employee.Print();
	cout << endl;
	Person* pPerson = &person;
	pPerson->Print();		//calls print in person
	cout << endl;
	pPerson = &student;
	pPerson->Print();		//calls print in student
	cout << endl;
	pPerson = &emloyee;
	pPerson->Print();		//calls print in employee
}

thanks in advance for your help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
#include "Person.h"

namespace std;

Person::Person(string stName)
:m_stName(stName)
{
	//Empty
}
void Person::Print() const
{
	cout << "Name: " << m_stName << endl;
}

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.

Содержание

  1. Syntax error identifier что это
  2. ошибка C2061: синтаксическая ошибка: идентификатор, но заголовочный файл уже включен
  3. Решение
  4. Syntax error identifier что это
  5. Answered by:
  6. Question
  7. Answers
  8. Syntax error identifier что это
  9. Answered by:
  10. Question
  11. Answers
  12. All replies
  13. 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 replies

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:

Ah I see. Why dont I have access to that constructor though?
That must be it I just dont understand why

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)
<
System: tring ^sip=gcnew System: tring(ip);
System::UInt16 ^sport = gcnew System::UInt16(port);
System: tring ^sdata = gcnew System: tring(data);

Источник

Syntax error identifier что это

Это основывается на предыдущее мое сообщение, но поскольку тема другая я вывел это в отдельную ветку.
Есть код(приведен ниже) на который компайлер кричит. Почему.
Вот такие ошибки пишет:

Error 1 error C2061: syntax error : identifier ‘ElementType’
Error 2 error C2059: syntax error : ‘;’
Error 3 error C2061: syntax error : identifier ‘List’
Error 4 error C2059: syntax error : ‘>’
Error 5 error C2016: C requires that a struct or union has at least one member
Error 6 error C2061: syntax error : identifier ‘AssetDetails’
Error 7 error C2059: syntax error : ‘>’
Error 8 error C2061: syntax error : identifier ‘ElementType’
Error 9 error C2059: syntax error : ‘;’
Error 10 error C2016: C requires that a struct or union has at least one member
Error 11 error C2061: syntax error : identifier ‘ElementType’
Error 12 error C2059: syntax error : ‘>’
Error 13 error C2061: syntax error : identifier ‘ElementType’
Error 14 error C2059: syntax error : ‘;’

От: Alexey F
Дата: 08.06.09 17:41
Оценка:

Здравствуйте, TheAteist, Вы писали:

Во-первых (из другого топика):
«Кажется я понял
Значит премерно вот так получается, да?»
Да, так.

Во-вторых (взято из уже удалённого сообщения):

TA>Вот часть другого кода(приведен ниже) на который компайлер тоже кричит
TA>почему на «typedef» он тоже кричит?

Вот почему (см. выделенное):
TA>

Нужно разорвать циклическую зависимость. Лучше, переработав заголовки.

От: TheAteist
Дата: 08.06.09 17:55
Оценка:

Здравствуйте, Alexey F, Вы писали:

AF>Во-вторых (взято из уже удалённого сообщения):
Я попытался стереть, т.к. вместо моего ника там стоял Аноним

Что я уже только не пробывал, чтоб это исправить эту циклическую зависимость.
Да, должно было быть «AssetDetails m_assetDetails» там где вы написали «Забыли указать имя переменной?»
1 — «typedef Demand ElementType» должен быть в list.h, т.к. он к нему относится
2 — а

должен быть в customer.h, т.к. он к нему относится

Как можно исправить?
(Я только учусь и все же благое дело вы совершаете в этов форуме )

AF>Вот почему (см. выделенное):
TA>>

AF>Нужно разорвать циклическую зависимость. Лучше, переработав заголовки.
AF>

От: TheAteist
Дата: 08.06.09 18:10
Оценка:

Кажется я нашел решение только не знаю почему так работает и правильно ли
в файле «list.h» я поменял

и в файле «customer.h» я поменял

От: Alexey F
Дата: 08.06.09 18:27
Оценка:
От: TheAteist
Дата: 08.06.09 18:33
Оценка:
От: Alexey F
Дата: 08.06.09 19:24
Оценка:

Здравствуйте, TheAteist, Вы писали:

TA>Маленькая поправка, List L не должен хранится в AssetDetails.
TA>должно было так
TA>

Так это совершенно другое дело!

Кажется я нашел решение только не знаю почему так работает и правильно ли
в файле «list.h» я поменял
на

и в файле «customer.h» я поменял
на

От: TheAteist
Дата: 08.06.09 19:50
Оценка:

Здравствуйте, Alexey F, Вы писали:

ошибка была потому-что уже имелось «typedef struct. » в «customer.h», а я добавил еше раз «typedef Demand ElementType» в «list.h»? как эта ошибка называется?
и почему хотя у меня имеется «#define NAME_LEN 20» который НЕ в #ifndef и подключается в нескольких файлах, то не происходит ошибки?

Огромное вам спасибо за помошь.

От: Alexey F
Дата: 08.06.09 20:08
Оценка:

Здравствуйте, TheAteist, Вы писали:

TA>ошибка была потому-что уже имелось «typedef struct. » в «customer.h», а я добавил еше раз «typedef Demand ElementType» в «list.h»? как эта ошибка называется?
Если я нигде не путаю и ничего не забыл, ошибка была в:

  • Циклической зависимости заголовочных файлов друг от друга;
  • Отсутствии предопределения типа Demand;
  • Т.к. Demand был typedef’ом — невозможности такого предопределения;

Он не знал, что Demand — это структура. «struct Demand;» или «typedef struct Demand ElementType;» дали ему такую подсказку.

TA>и почему хотя у меня имеется «#define NAME_LEN 20» который НЕ в #ifndef и подключается в нескольких файлах, то не происходит ошибки?
Так это же #define — директива препроцессора Это не переменная — до линкера дело здесь даже не доходит.

P.S. Как осободитесь, рекомендую Вам более детально просмотреть где-нибудь информацию про внутреннее/внешнее связывание и предварительные объявления структур.

Источник

Понравилась статья? Поделить с друзьями:
  • Ошибка c2059 синтаксическая ошибка using namespace
  • Ошибка c2212 00 заводской режим как снять
  • Ошибка c2039 c
  • Ошибка c2205 mitsubishi lancer 10
  • Ошибка c2010 kyocera 2040