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.
123k22 gold badges185 silver badges265 bronze badges
6
Я пытаюсь изучать 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
Вопрос:
это, вероятно, проблема включения, я получаю эти ошибки по всему коду, а не только для идентификатора строки, например 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
закончился полуколонами? Нет необходимости в этом.
Recommended Answers
Not sure if in Visual_Basic works like this, but in Borland C++ Builder worked just fine
void __fastcall TForm1::Button3Click(TObject *Sender) { int k; k=5 ; Label1->Caption = k; }
Jump to Post
Mixing C++/CLI and standard C++ can be troublesome. Try sticking to one or the other unless you have good reason not to:
label2->Text = Convert::ToString ( a );
Jump to Post
All 6 Replies
Not sure if in Visual_Basic works like this, but in Borland C++ Builder worked just fine
void __fastcall TForm1::Button3Click(TObject *Sender)
{
int k;
k=5 ;
Label1->Caption = k;
}
Looks like ye’ need to perform a good ol’ int-to-string conversion. Today we’ll be creating an ‘ostringstream’ object derived from the <sstream> library in order to facilitate our int-to-string needs:
#include<sstream>
#include<string>
#include<iostream>
using namespace std;
int main()
{
ostringstream int_to_str;
string temp;
int a = 0;
cout << "Enter a number fool: ";
cin >> a;
int_to_str << a;
temp = int_to_str.str();
cout << "String " << temp << " == int " << a;
return 0;
}
Edited
by Clinton Portis because:
you can’t fight the funk.
vidmaa, this doesn’t work with Visual.
Clinton, it does not work in my situation. I am sure it is going to work if I do it as console application. However it does not work with the Forms
Edited
by hajiakhundov because:
n/a
I looked around a bit, what I found out is that we actually need to convert an int to System::String. Who can help me with that?
Narue
5,707
Bad Cop
Team Colleague
Mixing C++/CLI and standard C++ can be troublesome. Try sticking to one or the other unless you have good reason not to:
label2->Text = Convert::ToString ( a );
Narue, thanks a lot! It worked finally
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
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();
};