|
pupsus 2 / 2 / 0 Регистрация: 30.10.2014 Сообщений: 62 |
||||
|
1 |
||||
|
12.11.2014, 18:38. Показов 28149. Ответов 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 |
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
| 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 }
Following bit of code is throwing error. I have no idea why. Can anyone shed some light?
All codes are on different files.
#ifndef MAINSESSION_H
#define MAINSESSION_H
#include "sessionsuper.h"
#include "mainwindow.h"
class MainSession : public SessionSuper
{
public:
MainSession();
private:
};
#include "mainsession.h"
MainSession::MainSession()
{
}
#endif // MAINSESSION_H
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "mainsession.h"
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
MainSession *ms; //Error here
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//ms=new MainSession(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
#ifndef SESSIONSUPER_H
#define SESSIONSUPER_H
class SessionSuper
{
public:
SessionSuper();
};
#endif // SESSIONSUPER_H
#include "sessionsuper.h"
SessionSuper::SessionSuper()
{
}
Error:
d:qtsrcuntitled4mainwindow.h:20: error: C2143: syntax error :
missing ‘;’ before ‘*’d:qtsrcuntitled4mainwindow.h:20: error: C4430: missing type
specifier — int assumed. Note: C++ does not support default-int
d:qtsrcuntitled4mainwindow.h:20: error: C4430: missing type
specifier — int assumed. Note: C++ does not support default-int
Am using Qt+msvc10.0 compiler.
Update:-
#ifndef MAINSESSION_H
#define MAINSESSION_H
#include "sessionsuper.h"
#include "mainwindow.h"
class MainSession : public SessionSuper
{
public:
MainSession(MainWindow*);
private:
MainWindow *mw;
};
#endif // MAINSESSION_H
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "mainsession.h"
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
MainSession *ms;
};
#endif // MAINWINDOW_H
#ifndef SESSIONSUPER_H
#define SESSIONSUPER_H
class SessionSuper
{
public:
SessionSuper();
};
#endif // SESSIONSUPER_H
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
#include "mainsession.h"
MainSession::MainSession(MainWindow mss)
{
mw=mss;
}
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//ms=new MainSession(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
#include "sessionsuper.h"
SessionSuper::SessionSuper()
{
}
Errors:- a lot more but of same type
asked Jul 30, 2013 at 10:55
4
You have circular include, forward declaration MainSession type to break the current circula include issue.
In MainWindow.h
//#include "mainsession.h" comment out this line
class MainSession; // add forward declaration
class MainWindow : public QMainWindow
{
//...
MainSession *ms; //Error here.
};
answered Jul 30, 2013 at 10:59
billzbillz
44.4k9 gold badges83 silver badges100 bronze badges
4
I have checked your code like this:
class MainWindow
{
public:
explicit MainWindow();
~MainWindow();
private:
Ui::MainWindow *ui;
MainSession *ms; //My error also here <- see this
};
See here in my code where MainSession is missing and I got same error in the line. Hope it will help. MainSession definition may missing because of file missing, file not included, scope problem (another namespace) etc. Please check these. namespace Ui (different) probably the problem.
answered Jul 30, 2013 at 11:22
pcbabupcbabu
2,2114 gold badges22 silver badges32 bronze badges
0
Problem Is Solved by using the observer Model.
A Complete Demo Here
Add a Comment If you want the working code of the above code.
Cheers!!!
answered Jul 30, 2013 at 12:57
Sayok88Sayok88
1,9981 gold badge13 silver badges22 bronze badges
Почему выдает ошибки?
Ошибки:
Ошибка 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;
}
};*/
};
-
Вопрос заданболее двух лет назад
-
398 просмотров
Не уверен по поводу чего большинство ошибок, но у тебя определены переменная и функция с одним именем. А так как они располагаются в одной области имен — это проблема. Вот и ругается Ошибка C2365 bankScore::score: переопределение; предыдущим определением было «данные-член» 31. Просто прочитай и все.
Пригласить эксперта
-
Показать ещё
Загружается…
13 июн. 2023, в 11:44
400 руб./за проект
13 июн. 2023, в 11:15
5000 руб./за проект
13 июн. 2023, в 11:01
30000 руб./за проект

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

