Oleg Pridarun 2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
||||
1 |
||||
02.07.2017, 13:05. Показов 7170. Ответов 12 Метки using namespace, visual studio, с, Синтаксис (Все метки)
У меня есть заголовочный файл LanguageEng.h В нём находится код:
При компиляции программы с этим заголовочным файлом происходит ошибка: c:users***onedriveпрограммыgamelanguageeng.h(4): error C2143: синтаксическая ошибка: отсутствие «;» перед «using namespace»
0 |
1642 / 1091 / 487 Регистрация: 17.07.2012 Сообщений: 5,345 |
|
02.07.2017, 13:53 |
2 |
Код программы в студию.
0 |
223 / 213 / 80 Регистрация: 26.04.2013 Сообщений: 972 |
|
02.07.2017, 14:08 |
3 |
Попробуйте добавить
0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
02.07.2017, 14:14 [ТС] |
4 |
Код программы в студию. Давайте я лучше весь проект кину, так как он многофайловый Добавлено через 5 минут
Попробуйте добавить Проблема осталась та же. Ни каких изменений
0 |
3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
02.07.2017, 16:40 |
5 |
Давайте я лучше весь проект кину И где же он?
0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
02.07.2017, 17:21 [ТС] |
6 |
И где же он? Хотел поместить его на гугл диск, но это, похоже заняло бы несколько часов (не знаю по какой причине). Скинуть код из файла с int main()?
0 |
3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
02.07.2017, 17:24 |
7 |
Хотел поместить его на гугл диск, но это, похоже заняло бы несколько часов (не знаю по какой причине). Здесь, в архиве, выложи. Или очень большой? Добавлено через 59 секунд
Скинуть код из файла с int main()? Хедеры, с определениями классов, есть в проекте?
0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
02.07.2017, 20:42 [ТС] |
8 |
Здесь, в архиве, выложи. Или очень большой? Добавлено через 59 секунд Хедеры, с определениями классов, есть в проекте? Классы не использовал. Я в них пока не разобрался. На данный момент только функции и переменные в хедерах
0 |
3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
02.07.2017, 20:56 |
9 |
Выкладывать проект будешь, или можно отписываться от темы?
0 |
5230 / 3202 / 362 Регистрация: 12.12.2009 Сообщений: 8,112 Записей в блоге: 2 |
|
03.07.2017, 15:11 |
10 |
нужно смотреть на файл, который инклюдит LanguageEng.h
0 |
с++ 1282 / 523 / 225 Регистрация: 15.07.2015 Сообщений: 2,562 |
|
03.07.2017, 15:18 |
11 |
так в этом файле и исправляй ошибку по пути так как LanguageEng.h и такой languageeng.h это разные файлы или нет?
0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
05.07.2017, 22:50 [ТС] |
12 |
Простите, мне отключили интернет. Проблему решил. languageeng и LanguageEng для Visual у меня одно и тоже. Проблема была в другом хедере. В нём была пропущена ;, и другие хедеры на это реагировали
0 |
Заблокирован |
|
05.07.2017, 23:01 |
13 |
Решение
Проблема была в другом хедере. Это было сразу очевидно.
1 |
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2143 |
Compiler Error C2143 |
11/04/2016 |
C2143 |
C2143 |
1d8d1456-e031-4965-9240-09a6e33ba81c |
Compiler Error C2143
syntax error : missing ‘token1’ before ‘token2’
The compiler expected a specific token (that is, a language element other than white space) and found another token instead.
Check the C++ Language Reference to determine where code is syntactically incorrect. Because the compiler may report this error after it encounters the line that causes the problem, check several lines of code that precede the error.
C2143 can occur in different situations.
It can occur when an operator that can qualify a name (::
, ->
, and .
) must be followed by the keyword template
, as in this example:
class MyClass { template<class Ty, typename PropTy> struct PutFuncType : public Ty::PutFuncType<Ty, PropTy> // error C2143 { }; };
By default, C++ assumes that Ty::PutFuncType
isn’t a template; therefore, the following <
is interpreted as a less-than sign. You must tell the compiler explicitly that PutFuncType
is a template so that it can correctly parse the angle bracket. To correct this error, use the template
keyword on the dependent type’s name, as shown here:
class MyClass { template<class Ty, typename PropTy> struct PutFuncType : public Ty::template PutFuncType<Ty, PropTy> // correct { }; };
C2143 can occur when /clr is used and a using
directive has a syntax error:
// C2143a.cpp // compile with: /clr /c using namespace System.Reflection; // C2143 using namespace System::Reflection;
It can also occur when you are trying to compile a source code file by using CLR syntax without also using /clr:
// C2143b.cpp ref struct A { // C2143 error compile with /clr void Test() {} }; int main() { A a; a.Test(); }
The first non-whitespace character that follows an if
statement must be a left parenthesis. The compiler cannot translate anything else:
// C2143c.cpp int main() { int j = 0; // OK if (j < 25) ; if (j < 25) // C2143 }
C2143 can occur when a closing brace, parenthesis, or semicolon is missing on the line where the error is detected or on one of the lines just above:
// C2143d.cpp // compile with: /c class X { int member1; int member2 // C2143 } x;
Or when there’s an invalid tag in a class declaration:
// C2143e.cpp class X { int member; } x; class + {}; // C2143 + is an invalid tag name class ValidName {}; // OK
Or when a label is not attached to a statement. If you must place a label by itself, for example, at the end of a compound statement, attach it to a null statement:
// C2143f.cpp // compile with: /c void func1() { // OK end1: ; end2: // C2143 }
The error can occur when an unqualified call is made to a type in the C++ Standard Library:
// C2143g.cpp // compile with: /EHsc /c #include <vector> static vector<char> bad; // C2143 static std::vector<char> good; // OK
Or there is a missing typename
keyword:
// C2143h.cpp template <typename T> struct X { struct Y { int i; }; Y memFunc(); }; template <typename T> X<T>::Y X<T>::memFunc() { // C2143 // try the following line instead // typename X<T>::Y X<T>::memFunc() { return Y(); }
Or if you try to define an explicit instantiation:
// C2143i.cpp // compile with: /EHsc /c // template definition template <class T> void PrintType(T i, T j) {} template void PrintType(float i, float j){} // C2143 template void PrintType(float i, float j); // OK
In a C program, variables must be declared at the beginning of the function, and they cannot be declared after the function executes non-declaration instructions.
// C2143j.c int main() { int i = 0; i++; int j = 0; // C2143 }
I am VERY new to C++ and Open GL and I have been trying to display 3D objects in a scene. it worked fine with one but when I tried to alter my code to add a second, my code regarding the HUD text showing the camera location started giving errors. The error above is shown and it is apparently in the sstream file (#include). I have tried searching around and asking for help but there is nothing that helps/that I understand. When I comment-out the #include line and the code that uses it, I get a similar saying «error C2143: syntax error : missing ‘;’ before ‘using'» in my main.cpp file.
I am running Visual Studio 2010 and I have even tried turning the whole thing off and on again, and copying the code over to a new project. Help would be greatly appreciated.
#include <Windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glut.h"
#include "SceneObject.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
//#include <cmath>
//#include <limits>
//#include <cstdlib>
using namespace std;
…
stringstream ss;
ss << "Camera (" << cam.pos.x << ", " << cam.pos.y << ", " << cam.pos.z << ")";
glClear(GL_DEPTH_BUFFER_BIT);
outputText(-1.0, 0.5, ss.str());
…
#ifndef SCENEOBJECT_H
#define SCENEOBJECT_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
struct point3D {
float x;
float y;
float z;
};
struct colour{
float r;
float g;
float b;
};
struct tri {
int a;
int b;
int c;
};
class SceneObject {
private:
int NUM_VERTS;
int NUM_COL;
int NUM_TRI;
point3D * vertices;
colour * colours;
tri * indices;
void drawTriangle(int a, int b, int c);
public:
SceneObject(const string fName) {
read_file(fName);
}
void drawShape()
{
// DO SOMETHING HERE
}
int read_file (const string fileName)
{
ifstream inFile;
inFile.open(fileName);
if (!inFile.good())
{
cerr << "Can't open file" << endl;
NUM_TRI = 0;
return 1;
}
//inFile >> shapeID;
inFile >> NUM_VERTS;
vertices = new point3D[NUM_VERTS];
for (int i=0; i < NUM_VERTS; i++)
{
inFile >> vertices[i].x;
inFile >> vertices[i].y;
inFile >> vertices[i].z;
}
inFile >> NUM_COL;
//inFile >> randomCol;
colours = new colour[NUM_COL];
/*if (randomCol == 'y')
{
for (int i=0; i < NUM_COL; i++)
{
colours[i].r = ((float) rand() / (RAND_MAX+1));
colours[i].g = ((float) rand() / (RAND_MAX+1));
colours[i].b = ((float) rand() / (RAND_MAX+1));
}
}
else if (randomCol == 'n')
{*/
for (int i=0; i < NUM_COL; i++)
{
inFile >> colours[i].r;
inFile >> colours[i].g;
inFile >> colours[i].b;
}
//}
inFile >> NUM_TRI;
indices = new tri[NUM_TRI];
for (int i=0; i < NUM_TRI; i++)
{
inFile >> indices[i].a;
inFile >> indices[i].b;
inFile >> indices[i].c;
}
inFile.close();
return 0;
}
}
#endif
I haven’t changed the code and as far as I am aware, there are semi-colons where there are meant to be. Even my friend who has been programming for 5 years couldn’t solve this. I will include any other specific code if needed. And when I said new to C++ and OpenGL I really much VERY new.
This is even my first post. I’ll get there eventually.
- Remove From My Forums
-
Вопрос
-
Подскажите, как подключить заголовочный файл в проекте Windows Forms. Создаю файл
header.h, определяю в нем небольшой класс и подключаю в главном файле проекта
cstring и этот header.h. При компиляции возникает ошибка
visual studio 2010projectsvisualisationvisualisationForm1.h(3): error C2143: синтаксическая ошибка: отсутствие «;» перед «namespace».Объясните пожалуйста что не так. Я начинающий, так что прошу сильно не пинать.
header.h
class c1 { int sp; int vd; char pt[80]; public: c1() {sp = 2; strcpy(pt, "\u.jpg");}; c1(int s, char p[80]) {sp = s; strcpy(pt,p);}; ~c1() {}; int getSp() {return sp;}; char getPt() {return pt[80];}; int getVd() {return vd;}; }
Main.cpp (Начало)
// Main.cpp: главный файл проекта. #include "stdafx.h" #include <cstring> #include "header.h" #include "Form1.h" using namespace Main;
Form1.h (Начало)
#pragma once namespace Main{ using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Сводка для Form1 /// </summary>
Ответы
-
В C++ обязательно должна ставиться точка с запятой в конце объявления класса:
Позвольте в свою очередь спросить, чем вызвано применение нативного C++ и C++/CLI вместе?
Ещё вот этот момент:
char getPt() {return pt[80];};
Явно ошибка. Что тут должно возвращаться?
-
Помечено в качестве ответа
8 ноября 2011 г. 19:25
-
Снята пометка об ответе
Sanyokbig
8 ноября 2011 г. 19:26 -
Помечено в качестве ответа
Abolmasov Dmitry
11 ноября 2011 г. 6:47
-
Помечено в качестве ответа
|
|
|
Компилятор не в себе
, глючит.. выдаёт ошибку там, где её быть не должно
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
после попытки компиляции программы в MVisual C++ 2008 Express пишет следующие тупые ошибки: Ошибка 1 error C2143: синтаксическая ошибка: отсутствие «;» перед «using» Ошибка 2 error C2628: недопустимый ‘Temperature’ с последующим ‘void’ (возможно, отсутствует ‘;’) //gradus.h #pragma once #include <iostream> #include <string> using namespace std; class Temperature { private: int grad; char sys; public: Temperature(int gr = 0 , char shkala = ‘C’) : grad(gr) , sys(shkala) {}; void set( int gr , char shkala) {grad = gr; sys = shkala;}; void set( string str); int change(); void show(); } //gradus.cpp #include «gradus.h» void Temperature::set(string str) {…} int Temperature::change() {…} void Temperature::show() {…} |
kanes |
|
При определении класса после } ставят ; |
Potroshitell |
|
аа.. сори, не компилятор глючит, а я! вопрос в топку Сообщение отредактировано: Potroshitell — 15.01.10, 13:46 |
kanes |
|
Цитата Potroshitell @ 15.01.10, 13:45 ааа, или возможно просто set — ключевое слово. не ключевое, но слово обозначающее контейнер из STL std::set, правда для него требуется заголовок <set> так что дело не в этом |
Potroshitell |
|
я ещё вот хотел бы задать 1 мини-вопросик.. ради него наверно не стоит создавать отдельную тему=) class Temperature { public: Temperature(int gr = 0 , char shkala = ‘C’) : grad(gr) , sys(shkala) {}; void set( int gr , char shkala) {grad = gr; sys = shkala;} /* вот тут. если функция определяется в классе как встроенная, то нужно ставить ; после } ? а то компилятор вроде не ругается в обоих случаях. */ … Сообщение отредактировано: Potroshitell — 15.01.10, 14:08 |
zim22 |
|
Junior Рейтинг (т): 3 |
Цитата Potroshitell @ 15.01.10, 14:07 если функция определяется в классе как встроенная, то нужно ставить ; после } ? не нужно. |
Potroshitell |
|
Mr.Delphist |
|
И это… того… Не пиши «using namespace» в заголовочных файлах, а то это очень «добрый» сюрприз себе на будущее |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ Script execution time: 0,0334 ] [ 16 queries used ] [ Generated: 8.06.23, 20:26 GMT ]