Error c2143 синтаксическая ошибка отсутствие перед строка

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

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

  • 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

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

eLg's user avatar

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.'s user avatar

Ed S.Ed S.

122k21 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 Howard's user avatar

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

lenik's user avatar

leniklenik

23k4 gold badges32 silver badges43 bronze badges

8

Содержание

  1. Ошибка компилятора C2143
  2. Compiler Error C2143
  3. Error c2143 syntax error missing before что это
  4. Answered by:
  5. Question
  6. Answers
  7. All replies
  8. Error c2143 syntax error missing before что это
  9. Asked by:
  10. Question
  11. All replies

Ошибка компилятора C2143

синтаксическая ошибка: отсутствует «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?

Источник

pupsus

2 / 2 / 0

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

Сообщений: 62

1

12.11.2014, 18:38. Показов 25761. Ответов 7

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


Вот текст класса, где собственно говоря вылезает ошибка. Где я мог пропустить «;» никак не пойму. Причем предыдущая строка «Field* field;» ничем не отличается от строки с ошибкой «CSprite* balls;»

C++ (Qt)
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
#pragma once
#include "stdafx.h"
#include "Sprite.h"
#include "Field.h"
 
 
class Balls
{
public:
    Balls(SDL_Renderer* passed_renderer, int x, int y, int w, int h, std::string FilePath);
    ~Balls(void);
 
    void Update();
 
    void SetColor();
    void Draw();
    void Generate();
    
private:
    Field* field;
    CSprite* balls;
    SDL_Renderer* renderer;
    int X;
    int Y;
    int img_width;
    int img_height;
};

текст ошибки:
1>—— Построение начато: проект: My_Game, Конфигурация: Debug Win32 ——
1> Sprite.cpp
1>c:usersсаняdocumentsvisual studio 2010projectsmy_gamemy_gameballs.h(21): error C2143: синтаксическая ошибка: отсутствие «;» перед «*»
1>c:usersсаняdocumentsvisual studio 2010projectsmy_gamemy_gameballs.h(21): error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>c:usersсаняdocumentsvisual studio 2010projectsmy_gamemy_gameballs.h(21): error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию
1> My_Game.cpp
1>c:usersсаняdocumentsvisual studio 2010projectsmy_gamemy_gameballs.h(21): error C2143: синтаксическая ошибка: отсутствие «;» перед «*»
1>c:usersсаняdocumentsvisual studio 2010projectsmy_gamemy_gameballs.h(21): error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>c:usersсаняdocumentsvisual studio 2010projectsmy_gamemy_gameballs.h(21): error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию
1> Main.cpp
1>c:usersсаняdocumentsvisual studio 2010projectsmy_gamemy_gameballs.h(21): error C2143: синтаксическая ошибка: отсутствие «;» перед «*»
1>c:usersсаняdocumentsvisual studio 2010projectsmy_gamemy_gameballs.h(21): error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>c:usersсаняdocumentsvisual studio 2010projectsmy_gamemy_gameballs.h(21): error C4430: отсутствует спецификатор типа — предполагается int. Примечание. C++ не поддерживает int по умолчанию
1> Создание кода…
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



16495 / 8988 / 2205

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

Сообщений: 15,611

12.11.2014, 18:48

2

Лучший ответ Сообщение было отмечено pupsus как решение

Решение

pupsus, эти ошибки говорят о том, что почему-то в этом месте трансляции не видно объявления типа CSprite.
Случайно файлы заголовочные друг от друга не зависят? Нет ли включения в Sprite.h файла Balls.h?



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

16495 / 8988 / 2205

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

Сообщений: 15,611

12.11.2014, 18:56

6

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

есть, а так нельзя делать?

Нельзя. Т.к. будет рекурсивное включение.
Используй предварительное объявление (например в Balls.h), а include «Sprite.h» из Balls.h убери

C++
1
2
3
class CSprite;
 
// код из шапки темы.

заголовочный файл Sprite.h подключай вместо этого в Balls.cpp

Добавлено через 25 секунд

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

а зачем у деструктора воид убирать?

Можно не убирать. Но вообще в С++ он не обязателен.



1



2 / 2 / 0

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

Сообщений: 62

12.11.2014, 19:02

 [ТС]

7

ясно, спасибо большое очень помогли



0



DrOffset

16495 / 8988 / 2205

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

Сообщений: 15,611

12.11.2014, 19:14

8

Лучший ответ Сообщение было отмечено pupsus как решение

Решение

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

если не сложно объясните в чем тут дело, почему не могут заголовочные друг на друга ссылаться?

А включает Б, а Б включает А. Это бесконечная рекурсия. Разрывает ее в данном случае pragma once, но в что-то в любом случае страдает, либо в Balls.h не видно содержимого Sprite, либо наоборот (в зависимости от того что вперед успело включиться).

Добавлено через 10 минут
pupsus,
Вот небольшая иллюстрация на примере include-guards defines (с ними нагляднее, чем с once), но смысл тот же.

C++
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
28
29
30
31
32
33
34
#ifndef A_TEST
#define A_TEST //A.h (1)
    //include "B.h"
    #ifndef B_TEST
    #define B_TEST
        //include "A.h"
        #ifndef A_TEST
        #define A_TEST //A.h(2)
            // и т.д.
 
            class A
            {
                B * f;
            };
        #endif
        // end include
 
        class B
        {
 
            A * f; // <-- здесь будет ошибка, A не объявлен,
                   // т.к. include guard выше не дал включить A.h
                   // потому что A_TEST уже есть, задефайнен выше (1)
        };
 
    #endif
    //end include
 
    class A
    {
        B * f;
    };
 
#endif //A_TEST



6



Это ошибка синтаксиса. Связана она с отсутствием необходимых разделителей между элементами языка. Компилятор ожидает, что некоторые элементы языка появятся прежде или после других элементов. Если этого не происходит, то он выдаем ошибку. Будем пробовать ее получить. Пишем код:

#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++ (лишние знаки, забытые ;)

ChA0S_f4me

Почему выдает ошибки?

Ошибки:

Ошибка 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;
            }
        };*/
};


  • Вопрос задан

    более двух лет назад

  • 307 просмотров

Не уверен по поводу чего большинство ошибок, но у тебя определены переменная и функция с одним именем. А так как они располагаются в одной области имен — это проблема. Вот и ругается Ошибка C2365 bankScore::score: переопределение; предыдущим определением было «данные-член» 31. Просто прочитай и все.

Пригласить эксперта


  • Показать ещё
    Загружается…

09 февр. 2023, в 15:06

2000 руб./за проект

09 февр. 2023, в 15:02

12000 руб./за проект

09 февр. 2023, в 14:22

1500 руб./за проект

Минуточку внимания

  • Forum
  • Beginners
  • error C2143: syntax error : missing ‘;’

error C2143: syntax error : missing ‘;’ before ‘<‘

error C2143: syntax error : missing ‘;’ before ‘<‘
error C4430: missing type specifier — int assumed. Note: C++ does not support default-int
error C2238: unexpected token(s) preceding ‘;’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#ifndef _lexicon_h
#define _lexicon_h


class Lexicon {
  public:
	/* Constructor: Lexicon                                                 */
	/* Constructor initializes a new lexicon to represent empty word list.  */
	Lexicon();

	/* Destructor: ~Lexicon                                                 */
	/* The destructor frees any storage associated with the lexicon.        */
	~Lexicon();

	/* Member function: getWordIterator                                     */
	/* This member function returns an iterator over all words contained    */
	/* in the lexicon in alphabetical order.                                */
	Iterator<string> getWordIterator();

};

#endif 

Was this maybe what you were looking for?
std::string::iterator getWordIterator();

can I add to the header
#include <string>

using namespace std;

rather than add the std:: prefix?

In a header file, I’d refrain from using the using namespace std; simply because you may run into issue later on. If you plan on keeping this is a local code and you’ve already used the using namespace call, then yes, string would be fine.

Just trying to show you properly rather than poor techniques.

thank you — always better to learn correctly, I will make the change to std::

are these correct:
bool containsWordHelper(nodeT *w, string word)
bool containsWordHelper(nodeT *w, std::string word)

void add(string word);
void add(std::string word)

Minus the missing semicolons, they appear to be.

Also, if in doubt, it doesn’t hurt to try putting std:: in front of it. Compile before and after and see if you get errors the second time.

Of what type is

Iterator

? I don’t see a declaration of

Iterator

nor do I see a header that could potentially house the declaration.

Wazzak

Last edited on

I edited it out for the example code

#include «iterator.h» and a few other headers are under #define _lexicon_h

Then, something you omitted is the cause. Paste the

Iterator

implementation (without omitting anything) here. If it’s a big file, use http://www.pastebin.org/

Wazzak

Last edited on

I believe they meant they omitted the header files to reduce the size of the paste. If Iterator was defined elsewhere, then you need to know how, and how it can be used.

My response was in regards as to what was shown and since they accepted the answer, I assumed it was what they were looking for.

Iterator could have been misspelled and they could have been confused on the implementation of it.

Edit: Sorry Framework, I just found this, and it’s above my head. Maybe you can help a little more?
http://www.cplusplus.com/forum/beginner/73046/

Last edited on

making the change to std:: solved the linker errors but creates a new problem.

the current edit:
Iterator<string> getWordIterator(); —> std::string::iterator getWordIterator();

now the compiler finds an issue with a mismatch between the declaration in the .h file and the call

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "stdafx.h" //first uncommented line http://www.pcreview.co.uk/forums/cant-use-std-lib-t3170870.html
#include <cstdlib> //added http://forums.devx.com/showthread.php?t=152439
#include <string>
#include <iostream>
#include <set>
#include <fstream> //CIFE seed
#include "genlib.h" //www.keithschwarz.com/cs106l/winter20072008/handouts/020_Writing_Without_Genlib.pdf
#include "simpio.h"
#include "set.h"
#include "lexicon.h"

using namespace std;

/* Constants */

const int MinChoice = 0;
const int MaxChoice = 11;

/* Prototypes */

void PrintRegExpMatches(string exp, Set<string> & matches);
void PrintCorrections(string seed, int editDistance,
					  Set<Lexicon::CorrectionT> & matches);
void PrintMenu();
int GetMenuChoice();
void NewLexicon(Lexicon * & lex);
void LoadWordsFromFile(Lexicon & lex);
void AddWord1(Lexicon & lex);
void ClassifyMeasurement(Lexicon & lex);
void ContainsPrefix(Lexicon & lex);
void PrintNumWords(Lexicon & lex);
void PrintWords(Lexicon & lex);
void RegExpMatch(Lexicon & lex);
void SuggestCorrections(Lexicon & lex);
void AutoSuggestCorrections(Lexicon & lex, string line);
void DoMenuChoice(Lexicon * & lex, int choice);

void PrintWords(Lexicon & lex)
{
	cout << "All activity codes in code list" << endl;
	cout << "--------------------" << endl;

	Iterator<string> it = lex.getWordIterator();
	while (it.hasNext()) {
		string line = it.next(); //CIFE seed code
		for(int i = 2; i < 16; i+=3) line.insert(i,".");
		//cout << it.next() << endl;
		cout << line << endl;
	}
}

error C2440: ‘initializing’ : cannot convert from ‘std::_String_iterator<_Elem,_Traits,_Alloc>’ to ‘Iterator<ElemType>’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx.h"
#include <cstdlib> //added http://forums.devx.com/showthread.php?t=152439
#include <string>
#include <iostream>
#include <fstream>
#include <set>
#include "genlib.h" //www.keithschwarz.com/cs106l/winter20072008/handouts/020_Writing_Without_Genlib.pdf
#include "simpio.h"
#include "lexicon.h"
#include "iterator.h"
#include "set.h" //added to match lexicon.h and main.cpp file 6/8/2012 - seemed to correct most (dozens) of errors


using namespace std;

Iterator<string> Lexicon::getWordIterator()
{
	Iterator<string> *iter = new Iterator<string>();
	allWordsHelper(root, "", iter);
	return *iter;
}

C2556: ‘Iterator<ElemType> Lexicon::getWordIterator(void)’ : overloaded function differs only by return type from ‘std::_String_iterator<_Elem,_Traits,_Alloc> Lexicon::getWordIterator(void)’

error C2371: ‘Lexicon::getWordIterator’ : redefinition; different basic types

I did not post the entire code, just the header and the function the compiler found the error in

I am going to revert the edit and try another path to a solution. The Iterator<string> getWordIterator(); compiled in a previous working version so i know it works. And, the edit created the template mismatch errors. I ma going to focus on the Linker errors and check the source files.

Topic archived. No new replies allowed.

Понравилась статья? Поделить с друзьями:
  • Error c2143 syntax error missing before type
  • Error c2143 syntax error missing before constant
  • Error c2131 выражение не определяется константой
  • Error c2131 expression did not evaluate to a constant
  • Error c2110 невозможно добавить два указателя