pupsus 2 / 2 / 0 Регистрация: 30.10.2014 Сообщений: 62 |
||||
1 |
||||
12.11.2014, 18:38. Показов 28152. Ответов 7 Метки нет (Все метки)
Вот текст класса, где собственно говоря вылезает ошибка. Где я мог пропустить «;» никак не пойму. Причем предыдущая строка «Field* field;» ничем не отличается от строки с ошибкой «CSprite* balls;»
текст ошибки:
0 |
17439 / 9269 / 2266 Регистрация: 30.01.2014 Сообщений: 16,230 |
|
12.11.2014, 18:48 |
2 |
Решениеpupsus, эти ошибки говорят о том, что почему-то в этом месте трансляции не видно объявления типа CSprite.
1 |
2 / 2 / 0 Регистрация: 30.10.2014 Сообщений: 62 |
|
12.11.2014, 18:50 [ТС] |
3 |
есть, а так нельзя делать?
0 |
16 / 16 / 6 Регистрация: 03.11.2014 Сообщений: 72 |
|
12.11.2014, 18:50 |
4 |
У деструктора воид убирать надо?
0 |
2 / 2 / 0 Регистрация: 30.10.2014 Сообщений: 62 |
|
12.11.2014, 18:54 [ТС] |
5 |
все, ошибка исправлена, спасибо) Добавлено через 49 секунд
0 |
DrOffset 17439 / 9269 / 2266 Регистрация: 30.01.2014 Сообщений: 16,230 |
||||
12.11.2014, 18:56 |
6 |
|||
есть, а так нельзя делать? Нельзя. Т.к. будет рекурсивное включение.
заголовочный файл Sprite.h подключай вместо этого в Balls.cpp Добавлено через 25 секунд
а зачем у деструктора воид убирать? Можно не убирать. Но вообще в С++ он не обязателен.
1 |
2 / 2 / 0 Регистрация: 30.10.2014 Сообщений: 62 |
|
12.11.2014, 19:02 [ТС] |
7 |
ясно, спасибо большое очень помогли
0 |
DrOffset 17439 / 9269 / 2266 Регистрация: 30.01.2014 Сообщений: 16,230 |
||||
12.11.2014, 19:14 |
8 |
|||
Решение
если не сложно объясните в чем тут дело, почему не могут заголовочные друг на друга ссылаться? А включает Б, а Б включает А. Это бесконечная рекурсия. Разрывает ее в данном случае pragma once, но в что-то в любом случае страдает, либо в Balls.h не видно содержимого Sprite, либо наоборот (в зависимости от того что вперед успело включиться). Добавлено через 10 минут
6 |
Содержание
- Ошибка компилятора C2143
- Compiler Error C2143
- Error c2143 syntax error missing before что это
- Answered by:
- Question
- Answers
- All replies
- Error c2143 syntax error missing before что это
- Asked by:
- Question
- All replies
синтаксическая ошибка: отсутствует «token1» перед «token2»
Компилятор ожидал определенный маркер (т. е. элемент языка, отличный от пробела) и нашел вместо него другой маркер.
Проверьте справочник по языку C++ , чтобы определить, где код синтаксически неверен. Так как компилятор может сообщить об этой ошибке после обнаружения строки, которая вызывает проблему, проверьте несколько строк кода, предшествующих ошибке.
C2143 может возникать в разных ситуациях.
Это может произойти, когда за оператором, который может квалифицировать имя ( :: , -> и . ), должно следовать ключевое слово template , как показано в следующем примере:
По умолчанию В C++ предполагается, что Ty::PutFuncType это не шаблон, поэтому следующее интерпретируется как знак меньшего. Необходимо явно сообщить компилятору, что PutFuncType является шаблоном, чтобы он смог правильно проанализировать угловую скобку. Чтобы исправить эту ошибку, используйте ключевое template слово для имени зависимого типа, как показано ниже:
C2143 может возникать, если используется /clr и using директива имеет синтаксическую ошибку:
Это также может произойти при попытке скомпилировать файл исходного кода с помощью синтаксиса CLR без использования /clr:
Первый символ без пробелов, следующий за оператором if , должен быть левой скобкой. Компилятор не может перевести ничего другого:
C2143 может возникать, когда закрывающая фигурная скобка, круглые скобки или точка с запятой отсутствуют в строке, в которой обнаружена ошибка, или в одной из строк выше:
Или при наличии недопустимого тега в объявлении класса:
Или, если метка не присоединена к оператору. Если необходимо поместить метку сама по себе, например в конце составного оператора, прикрепите ее к оператору NULL:
Эта ошибка может возникать, когда выполняется неквалифицированный вызов типа в стандартной библиотеке C++:
Или отсутствует ключевое typename слово:
Или при попытке определить явное создание экземпляра:
В программе C переменные должны быть объявлены в начале функции и не могут быть объявлены после того, как функция выполнит инструкции, не являющиеся объявлениями.
Источник
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:
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:
C2143 can occur when /clr is used and a using directive has a syntax error:
It can also occur when you are trying to compile a source code file by using CLR syntax without also using /clr:
The first non-whitespace character that follows an if statement must be a left parenthesis. The compiler cannot translate anything else:
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:
Or when there’s an invalid tag in a class declaration:
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:
The error can occur when an unqualified call is made to a type in the C++ Standard Library:
Or there is a missing typename keyword:
Or if you try to define an explicit instantiation:
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.
Источник
Error c2143 syntax error missing before что это
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
#ifndef DEPT_INCLUDED
#define DEPT_INCLUDED
typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;
Error message is: «Error 1 error C2143: syntax error : missing ‘;’ before ‘ ‘» and it is point to «typedef struct <» line.
Can somebody help? Thanks.
Answers
typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;
it’s:
typedef unsigned long int UL;
You should include this typedef before the structure definition!
#ifndef DEPT_INCLUDED
#define DEPT_INCLUDED
typedef unsigned long UL;
typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;
#endif
Microsoft MVP — Visual C++
Blog: http://nibuthomas.com Posts are provided as is without warranties or guaranties.
What happens if you temporary put the expected ‘;’ before typedef? What is the first error displayed?
typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;
If you’re using C++ why can’t you just do this:
There are 10 types of people in this world; those who understand binary and those who don’t.
I tried using the that code above but still.
‘CompileAs’ propertry for this project has been set to C++.
#ifndef DEPT_INCLUDED
#define DEPT_INCLUDED
typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;
#endif
Источник
Error c2143 syntax error missing before что это
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Asked by:
Question
Ok.. so I decide to start learning some inteligence and start in Visual C++ latest down load, get the turorials suggested which are great and get cracking at it.
After the fourth lesson I get the following build error
c:program filesmicrosoft visual studio 9.0vcincludeistream(13) : error C2143: syntax error : missing ‘;’ before ‘namespace’
the only difference with the various lesson projects I have been working on is the actual code
after typing the attached code I am unable to build all previous project lessons, I did the whole reboot thing and still the same problem?
Go to the directory indicated in the error message:
c:program filesmicrosoft visual studio 9.0vcinclude
Open the file istream with an editor or viewer. (Notepad will do.)
Copy and paste the first 20 lines of that file into a post here.
I suspect that you have a missing semi-colon or closing brace in your stdafx.h header file. You should begin your search there.
Best Wishes,
-David Delaune
Quote>I suspect that you have a missing semi-colon or closing brace in your stdafx.h header file
Note that the OP said:
Quote>after typing the attached code I am unable to build all previous project lessons
I take this to mean that projects which previously built cleanly will no longer do so.
Since each project should have it’s own stdafx.h it seems unlikely that this is the
source of the problem.
Note that the error message says:
missing ‘;’ before ‘namespace’
and points to line 13 of the header istream.
I see no word «namespace» anywhere in the istream header of my installation.
Note that the error message says:
missing ‘;’ before ‘namespace’
and points to line 13 of the header istream.
I see no word «namespace» anywhere in the istream header of my installation.
Check your definition of _STD_BEGIN.
Best Wishes,
-David Delaune
Quote>Check your definition of _STD_BEGIN.
Will no-one rid me of these meddlesome macros?
Good catch. Thanks.
That is correct regarding all the previous compiled projects, I have attached the requested code
That looks kosher, so the problem is probably earlier.
Looking at the include chain from iostream, it pulls in istream which pulls in ostream
which pulls in ios which pulls in xlocnum which pulls in climits, etc. etc. Before that,
stdafx.h pulls in targetver.h etc. etc. All of the above are pulled in (at least a few
dozen files) before we reach line 13 of istream where the error occurs.
First, go to the Project Properties and under
Configuration Properties=>C/C++=>Advanced
set the field «Show Includes» to «Yes» then click on «Apply/OK».
Go to the output window, select all of the lines, copy to Windows clipboard
and paste here in a message.
Second, answer these questions:
(1) Did you give each project its own name, or did you use the same name for each
project?
(2) Click on the Build menu, then click on «Clean Solution». Rebuild. Does the
problem persist?
(3) If the problem is still there, go to the Project Properties and under
Configuration Properties=>C/C++=>Precompiled Headers
set «Create/Use Precompiled Header» to «Not Using Precompiled Headers»
then click on «Apply/OK». Rebuild. Does the problem persist?
Источник
I am new to programming C.. please tell me what is wrong with this program, and why I am getting this error: error C2143: syntax error : missing ‘;’ before ‘type’….
extern void func();
int main(int argc, char ** argv){
func();
int i=1;
for(;i<=5; i++) {
register int number = 7;
printf("number is %dn", number++);
}
getch();
}
asked Mar 29, 2013 at 4:10
8
Visual Studio only supports C89. That means that all of your variables must be declared before anything else at the top of a function.
EDIT: @KeithThompson prodded me to add a more technically accurate description (and really just correct where mine is not in one regard). All declarations (of variables or of anything else) must precede all statements within a block.
answered Mar 29, 2013 at 4:17
Ed S.Ed S.
122k22 gold badges182 silver badges263 bronze badges
2
I haven’t used visual in at least 8 years, but it seems that Visual’s limited C compiler support does not allow mixed code and variables. Is the line of the error on the declaration for int i=1;
?? Try moving it above the call to func();
Also, I would use extern void func(void);
answered Mar 29, 2013 at 4:18
Randy HowardRandy Howard
2,18016 silver badges26 bronze badges
this:
int i=1;
for(;i<=5; i++) {
should be idiomatically written as:
for(int i=1; i<=5; i++) {
because there no point to declare for
loop variable in the function scope.
answered Mar 29, 2013 at 4:17
leniklenik
23.2k4 gold badges34 silver badges43 bronze badges
8
Перейти к контенту
- Remove From My Forums
-
Question
-
The line of code which is causing this error is:-
CD3DVertexCache *m_pVertexCache;
CD3DVertexCache is a class. Usually this is a stupid error meaning I’ve not included the header file for the class. However on this occasion I have included the header file for the class. Further more when I run the mouse cursor over the class name the little message box appears class CD3DVertexCache. Which tells me the compiler knows of the class identifier. I’m not sure why I’m getting the error message, wondering if someone can advise what other situations would cause this error to appear?
Thanks,
Paul.
Answers
-
Usually means that there is an error or omission in the previous line(s).
Check for a missing semi-colon or other error(s) in the line(s) immediately
*before* the one indicated by the error message.
Check also for a missing semi-colon at the end of class and structure definitions.
— Wayne
pupsus 2 / 2 / 0 Регистрация: 30.10.2014 Сообщений: 62 |
||||
1 |
||||
12.11.2014, 18:38. Показов 25532. Ответов 7 Метки нет (Все метки)
Вот текст класса, где собственно говоря вылезает ошибка. Где я мог пропустить «;» никак не пойму. Причем предыдущая строка «Field* field;» ничем не отличается от строки с ошибкой «CSprite* balls;»
текст ошибки:
__________________ 0 |
16466 / 8966 / 2198 Регистрация: 30.01.2014 Сообщений: 15,566 |
|
12.11.2014, 18:48 |
2 |
Решениеpupsus, эти ошибки говорят о том, что почему-то в этом месте трансляции не видно объявления типа CSprite. 1 |
2 / 2 / 0 Регистрация: 30.10.2014 Сообщений: 62 |
|
12.11.2014, 18:50 [ТС] |
3 |
есть, а так нельзя делать? 0 |
16 / 16 / 6 Регистрация: 03.11.2014 Сообщений: 72 |
|
12.11.2014, 18:50 |
4 |
У деструктора воид убирать надо? 0 |
2 / 2 / 0 Регистрация: 30.10.2014 Сообщений: 62 |
|
12.11.2014, 18:54 [ТС] |
5 |
все, ошибка исправлена, спасибо) Добавлено через 49 секунд 0 |
DrOffset 16466 / 8966 / 2198 Регистрация: 30.01.2014 Сообщений: 15,566 |
||||
12.11.2014, 18:56 |
6 |
|||
есть, а так нельзя делать? Нельзя. Т.к. будет рекурсивное включение.
заголовочный файл Sprite.h подключай вместо этого в Balls.cpp Добавлено через 25 секунд
а зачем у деструктора воид убирать? Можно не убирать. Но вообще в С++ он не обязателен. 1 |
2 / 2 / 0 Регистрация: 30.10.2014 Сообщений: 62 |
|
12.11.2014, 19:02 [ТС] |
7 |
ясно, спасибо большое очень помогли 0 |
DrOffset 16466 / 8966 / 2198 Регистрация: 30.01.2014 Сообщений: 15,566 |
||||
12.11.2014, 19:14 |
8 |
|||
Решение
если не сложно объясните в чем тут дело, почему не могут заголовочные друг на друга ссылаться? А включает Б, а Б включает А. Это бесконечная рекурсия. Разрывает ее в данном случае pragma once, но в что-то в любом случае страдает, либо в Balls.h не видно содержимого Sprite, либо наоборот (в зависимости от того что вперед успело включиться). Добавлено через 10 минут
6 |
I am new to programming C.. please tell me what is wrong with this program, and why I am getting this error: error C2143: syntax error : missing ‘;’ before ‘type’….
extern void func();
int main(int argc, char ** argv){
func();
int i=1;
for(;i<=5; i++) {
register int number = 7;
printf("number is %dn", number++);
}
getch();
}
asked Mar 29, 2013 at 4:10
9
Visual Studio only supports C89. That means that all of your variables must be declared before anything else at the top of a function.
EDIT: @KeithThompson prodded me to add a more technically accurate description (and really just correct where mine is not in one regard). All declarations (of variables or of anything else) must precede all statements within a block.
answered Mar 29, 2013 at 4:17
Ed S.Ed S.
121k21 gold badges181 silver badges262 bronze badges
2
I haven’t used visual in at least 8 years, but it seems that Visual’s limited C compiler support does not allow mixed code and variables. Is the line of the error on the declaration for int i=1;
?? Try moving it above the call to func();
Also, I would use extern void func(void);
answered Mar 29, 2013 at 4:18
Randy HowardRandy Howard
2,16015 silver badges26 bronze badges
this:
int i=1;
for(;i<=5; i++) {
should be idiomatically written as:
for(int i=1; i<=5; i++) {
because there no point to declare for
loop variable in the function scope.
answered Mar 29, 2013 at 4:17
leniklenik
22.9k4 gold badges32 silver badges43 bronze badges
8
I am extremely confused why I am getting this strange error all the sudden:
Time.h is a very simple class, and it has a semicolon at the end of the class description, so I am pretty sure my code is correct here.. Then I get the same errors in: Microsoft Visual Studio 10.0VCincludememory.. Any ideas!?!? Thanks!
Compiler Output
1>ClCompile:
1> Stop.cpp
1>c:projectnextbusTime.h(17): error C2143: syntax error : missing ';' before 'using'
1>c:projectnextbusTime.h(17): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1> NextBusDriver.cpp
1>C:Program Files (x86)Microsoft Visual Studio 10.0VCincludememory(16): error C2143: syntax error : missing ';' before 'namespace'
1>C:Program Files (x86)Microsoft Visual Studio 10.0VCincludememory(16): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Update:
Can’t really post all the code as this is for a school project and we aren’t supposed to post before we submit, but small snippets should be ok..
Time.h
#ifndef TIME_HPP
#define TIME_HPP
#include <string>
#include <sstream>
using namespace std;
class Time {
// Defines a time in a 24 hour clock
public:
// Time constructor
Time(int hours = 0 , int minutes= 0);
// POST: Set hours int
void setHours(int h);
// POST: Set minutes int
void setMinutes(int m);
// POST: Returns hours int
int getHours();
// POST: Returns minutes int
int getMinutes();
// POST: Returns human readable string describing the time
// This method can be overridden in inheriting classes, so should be virtual so pointers will work as desired
string toString();
private:
string intToString(int num);
// POST: Converts int to string type
int hours_;
int minutes_;
};
#endif
DepartureTime.h (inherited class)
#ifndef DEPARTURE_TIME_HPP
#define DEPARTURE_TIME_HPP
#include <string>
#include "Time.h"
using namespace std;
class DepartureTime: public Time {
public:
// Departure Time constructor
DepartureTime(string headsign, int hours=0, int minutes=0) : Time(hours, minutes), headsign_(headsign) { }
// POST: Returns bus headsign
string getHeadsign();
// POST: Sets the bus headsign
void setHeadsign(string headsign);
// POST: Returns human readable string describing the departure
string toString();
private:
// Class variables
string headsign_;
};
#endif
I am extremely confused why I am getting this strange error all the sudden:
Time.h is a very simple class, and it has a semicolon at the end of the class description, so I am pretty sure my code is correct here.. Then I get the same errors in: Microsoft Visual Studio 10.0VCincludememory.. Any ideas!?!? Thanks!
Compiler Output
1>ClCompile:
1> Stop.cpp
1>c:projectnextbusTime.h(17): error C2143: syntax error : missing ';' before 'using'
1>c:projectnextbusTime.h(17): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1> NextBusDriver.cpp
1>C:Program Files (x86)Microsoft Visual Studio 10.0VCincludememory(16): error C2143: syntax error : missing ';' before 'namespace'
1>C:Program Files (x86)Microsoft Visual Studio 10.0VCincludememory(16): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Update:
Can’t really post all the code as this is for a school project and we aren’t supposed to post before we submit, but small snippets should be ok..
Time.h
#ifndef TIME_HPP
#define TIME_HPP
#include <string>
#include <sstream>
using namespace std;
class Time {
// Defines a time in a 24 hour clock
public:
// Time constructor
Time(int hours = 0 , int minutes= 0);
// POST: Set hours int
void setHours(int h);
// POST: Set minutes int
void setMinutes(int m);
// POST: Returns hours int
int getHours();
// POST: Returns minutes int
int getMinutes();
// POST: Returns human readable string describing the time
// This method can be overridden in inheriting classes, so should be virtual so pointers will work as desired
string toString();
private:
string intToString(int num);
// POST: Converts int to string type
int hours_;
int minutes_;
};
#endif
DepartureTime.h (inherited class)
#ifndef DEPARTURE_TIME_HPP
#define DEPARTURE_TIME_HPP
#include <string>
#include "Time.h"
using namespace std;
class DepartureTime: public Time {
public:
// Departure Time constructor
DepartureTime(string headsign, int hours=0, int minutes=0) : Time(hours, minutes), headsign_(headsign) { }
// POST: Returns bus headsign
string getHeadsign();
// POST: Sets the bus headsign
void setHeadsign(string headsign);
// POST: Returns human readable string describing the departure
string toString();
private:
// Class variables
string headsign_;
};
#endif
Это ошибка синтаксиса. Связана она с отсутствием необходимых разделителей между элементами языка. Компилятор ожидает, что некоторые элементы языка появятся прежде или после других элементов. Если этого не происходит, то он выдаем ошибку. Будем пробовать ее получить. Пишем код:
#include "stdafx.h" int main(int argc, char* argv[]) { int x; int y; if (x<y) : // двоеточие здесь совсем не нужно { } }
Результат работы компилятора:
D:VСTestErrorTestError.cpp(10) : error C2143: syntax error : missing ';' before ':'
Второй наиболее частый вариант это забыть поставить «;» после объявления класса.
#include "stdafx.h" class CMy { } // забыли ";" class CMy2 { } int main(int argc, char* argv[]) { }
Опять та же ошибка.
D:VСTestErrorTestError.cpp(12) : error C2236: unexpected 'class' 'CMy2' D:VСTestErrorTestError.cpp(12) : error C2143: syntax error : missing ';' before '{'
Еще один вариант с лишней скобки:
#include "stdafx.h" int main(int argc, char* argv[]) { } // это лишнее return 0; }
Опять та же ошибка:
D:VСTestErrorTestError.cpp(11) : warning C4508: 'main' : function should return a value; 'void' return type assumed D:VСTestErrorTestError.cpp(12) : error C2143: syntax error : missing ';' before 'return'
Отсутствие закрывающей скобки может привести к такой же ошибке:
#include "stdafx.h" int main(int argc, char* argv[]) { for (int x=0;x<10;x++ // не хватает ")" { } return 0; }
Как видите это ошибка связанна с синтаксисом. Если она у Вас появляется внимательно просмотрите код на предмет соответствия требованиям C++ (лишние знаки, забытые
- Remove From My Forums
-
Question
-
int main(array<System::String ^> ^args) { // Enabling Windows XP visual effects before any controls are created Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); // Create the main window and run it Application::Run(gcnew Form1()); error at this line --> Form1.textBox1="hello";//(MYREC*)pMyCDS->lpData; return 0; }
hello dear forum
this above code gives folowing errors when compiling
1>.receiving.cpp(48) : error C2143: syntax error : missing ‘;’ before ‘.’
1>.receiving.cpp(48) : error C2143: syntax error : missing ‘;’ before ‘.’
how can I proceed ?
thank you
- Edited by
Thursday, August 28, 2014 2:20 PM
- Edited by
Answers
-
My bad. Sorry, my brain was thinking in C#, not C++/CLI. (The C# and C++ posts are combined when I view them).
Regardless, the advice doesn’t change much. Somewhere, InitializeComponent() is being called in one of your *.cpp source files. Use Control-Shift-F12 to locate it.
The line you need to insert will look something like:
textBox1->text = L»hello»;
- Marked as answer by
May Wang — MSFT
Friday, September 12, 2014 7:49 AM
- Marked as answer by
-
Further to my last post and Brian’s, try this:
In the Form1.h design window — where you have the graphical view of your program — double-click
anywhere on the main form. The editor should open the Form1.h (text) file for you to edit.Look for the constructor for Form1. It should look like this:
public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // }
Add the line to put «Hello» in textBox1.
public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // textBox1->Text = "Hello"; // add here OR in the Form1_Load handler }
Note that C++/CLI usually uses -> where C# and VB use a period (.).
An alternative place to put it rather than in the ctor would be in the Form1 load event code.
The handler code for this event should have been created automatically near the bottom of
Form1.h when you double-clicked on the main form in the designer.
#pragma endregion private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) { textBox1->Text = "Hello"; // add it here OR in the ctor }
— Wayne
- Edited by
WayneAKing
Friday, August 29, 2014 8:34 AM - Marked as answer by
May Wang — MSFT
Friday, September 12, 2014 7:49 AM
- Edited by
-
ok guys , I understand
this is completeley different than C
why I bothered you with all these questions
I want receive a data sent from another application with SendMessage function
Application::Run(gcnew Form1()); .................... if (WM_COPYDATA){ pMyCDS = lParam; xyz->textBox1->Text=(MYREC*)pMyCDS->lpData; ..................... the code between dotted lines should be in an infinite loop to detect coming data
the code between dotted lines should be in an infinite loop to detect coming data
if the code never gets below this line
Application::Run(gcnew Form1());
how it is posible to get and display the incoming data ?
If you need to change the text periodically, then use a timer: open the form in Form Designer (double click on Form1.h in Solution Explorer) and drag a
Timer component to your form. Then handle the Tick event (double click on the newly added component). Set the
Enabled property to true to start the timer automatically.For simple tests, try this in the Tick handler:
System::Void timer1_Tick( System::Object^ sender, System::EventArgs^ e ) { textBox1->Text = DateTime::Now.ToLongTimeString(); }
- Marked as answer by
May Wang — MSFT
Friday, September 12, 2014 7:48 AM
- Marked as answer by
- Remove From My Forums
-
Question
-
int main(array<System::String ^> ^args) { // Enabling Windows XP visual effects before any controls are created Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); // Create the main window and run it Application::Run(gcnew Form1()); error at this line --> Form1.textBox1="hello";//(MYREC*)pMyCDS->lpData; return 0; }
hello dear forum
this above code gives folowing errors when compiling
1>.receiving.cpp(48) : error C2143: syntax error : missing ‘;’ before ‘.’
1>.receiving.cpp(48) : error C2143: syntax error : missing ‘;’ before ‘.’
how can I proceed ?
thank you
- Edited by
Thursday, August 28, 2014 2:20 PM
- Edited by
Answers
-
My bad. Sorry, my brain was thinking in C#, not C++/CLI. (The C# and C++ posts are combined when I view them).
Regardless, the advice doesn’t change much. Somewhere, InitializeComponent() is being called in one of your *.cpp source files. Use Control-Shift-F12 to locate it.
The line you need to insert will look something like:
textBox1->text = L»hello»;
- Marked as answer by
May Wang — MSFT
Friday, September 12, 2014 7:49 AM
- Marked as answer by
-
Further to my last post and Brian’s, try this:
In the Form1.h design window — where you have the graphical view of your program — double-click
anywhere on the main form. The editor should open the Form1.h (text) file for you to edit.Look for the constructor for Form1. It should look like this:
public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // }
Add the line to put «Hello» in textBox1.
public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // textBox1->Text = "Hello"; // add here OR in the Form1_Load handler }
Note that C++/CLI usually uses -> where C# and VB use a period (.).
An alternative place to put it rather than in the ctor would be in the Form1 load event code.
The handler code for this event should have been created automatically near the bottom of
Form1.h when you double-clicked on the main form in the designer.
#pragma endregion private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) { textBox1->Text = "Hello"; // add it here OR in the ctor }
— Wayne
- Edited by
WayneAKing
Friday, August 29, 2014 8:34 AM - Marked as answer by
May Wang — MSFT
Friday, September 12, 2014 7:49 AM
- Edited by
-
ok guys , I understand
this is completeley different than C
why I bothered you with all these questions
I want receive a data sent from another application with SendMessage function
Application::Run(gcnew Form1()); .................... if (WM_COPYDATA){ pMyCDS = lParam; xyz->textBox1->Text=(MYREC*)pMyCDS->lpData; ..................... the code between dotted lines should be in an infinite loop to detect coming data
the code between dotted lines should be in an infinite loop to detect coming data
if the code never gets below this line
Application::Run(gcnew Form1());
how it is posible to get and display the incoming data ?
If you need to change the text periodically, then use a timer: open the form in Form Designer (double click on Form1.h in Solution Explorer) and drag a
Timer component to your form. Then handle the Tick event (double click on the newly added component). Set the
Enabled property to true to start the timer automatically.For simple tests, try this in the Tick handler:
System::Void timer1_Tick( System::Object^ sender, System::EventArgs^ e ) { textBox1->Text = DateTime::Now.ToLongTimeString(); }
- Marked as answer by
May Wang — MSFT
Friday, September 12, 2014 7:48 AM
- Marked as answer by
Почему выдает ошибки?
Ошибки:
Ошибка C2143 синтаксическая ошибка: отсутствие «;» перед «}» 74
Ошибка C2143 синтаксическая ошибка: отсутствие «;» перед «<<» 33
Ошибка C2059 синтаксическая ошибка: } 74
Ошибка C4430 отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию 33
Ошибка C2238 непредвиденные лексемы перед «;» 33
Ошибка C2365 bankScore::score: переопределение; предыдущим определением было «данные-член» 31
Сам код:
class bankScore
{
private:
int score = 100,
scoreNum = 945794982938456;
bool setedSum = false,
editedNum = false,
closed = false;
public:
/*void withdraw(int s)
{
if (score - s >= 0)
{
score -= s;
cout << "Деньги успешно сняты";
}
else {
cout << "У вас не хватает денег на счету!";
}
};
void deposit(int s)
{
score -= s;
cout << "Деньги успешно внесены";
};*/
void score()
{
cout << "На вашем счету " << score << " рублей 00 копеек";
};
/*void editScore()
{
if (!editedNum)
{
cout << "Введите новый номер счета (15 цифр): ";
cin >> scoreNum;
cout << "nУспешно!";
editedNum = true;
}
};
void closeScore()
{
if (!closed)
{
cout << "Если вы закроете счет, вы больше не сможете им воспользоваться, а так-же заново открыть его. Вы уверенны?n1. Уверен(-а)n2. Отмена";
int yes = _getch();
switch (yes)
{
case 49:
cout << "Счет закрыт. До свидания!";
case 50:
cout << "Закрытие счета отменено!";
break;
}
closed = true;
}
};
void setScore(int s)
{
if (!setedSum)
{
cout << "Введите сумму: ";
cin >> score;
cout << "nУспешно! Сейчас произведется отчистка" << endl;
_getch();
system("cls");
setedSum = true;
}
};*/
};
-
Вопрос заданболее двух лет назад
-
298 просмотров
Не уверен по поводу чего большинство ошибок, но у тебя определены переменная и функция с одним именем. А так как они располагаются в одной области имен — это проблема. Вот и ругается Ошибка C2365 bankScore::score: переопределение; предыдущим определением было «данные-член» 31. Просто прочитай и все.
Пригласить эксперта
-
Показать ещё
Загружается…
28 янв. 2023, в 22:48
500 руб./за проект
28 янв. 2023, в 20:58
30000 руб./за проект
28 янв. 2023, в 20:46
50000 руб./за проект
Минуточку внимания
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 }