Qt ошибка expected class name before token

I’m getting the error «expected class-name before ‘{‘ token» in my C++ Qt project. After googling it, it seems like its a problem of circular includes. I have pawn.h that includes piece.h, which includes board.h, which completes the circle by including pawn.h. I’ve read that this can be fixed with forward declarations, but I’ve tried forward declaring a few of problem classes, and it doesn’t work.

#ifndef PAWN_H
#define PAWN_H

#include "piece.h"

class Pawn : public Piece
{
    Q_OBJECT
public:
    explicit Pawn(QWidget *parent = 0);
};

#endif // PAWN_H

.

#ifndef PIECE_H
#define PIECE_H

#include <QWidget>
#include "board.h"

class Board;
class Piece : public QWidget
{
    Q_OBJECT
public:
    explicit Piece(QWidget *parent = 0);
    void setPosition(int rank, int file);
    QPixmap pixmap;

protected:
    void paintEvent(QPaintEvent *);

private:
    int rank;
    int file;
    int x;
    int y;
};

#endif // PIECE_H

.

#ifndef BOARD_H
#define BOARD_H

#include <QWidget>
#include <QVector>
#include <QGridLayout>
#include "square.h"
#include "pawn.h"
#include "knight.h"
#include "bishop.h"
#include "queen.h"
#include "king.h"

class Board : public QWidget
{
public:
    explicit Board(QWidget *parent = 0);
    QVector < QVector<Square *> > sqrVector;
    Pawn *pawn[8];

    Knight *knight[2];

    Bishop *bishop[2];

    Queen *queen;
    King *king;

private:
    QGridLayout *layout;
};

#endif // BOARD_H

Raketa

1 / 1 / 0

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

Сообщений: 197

1

02.05.2016, 12:14. Показов 4901. Ответов 20

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


Студворк — интернет-сервис помощи студентам

Что оно от меня хочет не могу понять,помогите пожалуйста(код класса прилагается)

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
#ifndef CHATDIALOG_H
#define CHATDIALOG_H
 
#include "ui_chatdialog.h"
#include "client.h"
 
class ChatDialog : public QDialog, private Ui::ChatDialog
{
    Q_OBJECT
 
public:
    ChatDialog(QWidget *parent = 0);
 
public slots:
    void appendMessage(const QString &from, const QString &message);
 
private slots:
    void returnPressed();
    void newParticipant(const QString &nick);
    void participantLeft(const QString &nick);
    void showInformation();
 
private:
    Client client;
    QString myNickName;
    QTextTableFormat tableFormat;
};
 
#endif



0



7533 / 6396 / 2916

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

Сообщений: 27,855

02.05.2016, 19:57

2

Что за Ui::ChatDialog? Это пространство имён так называется?



0



666 / 444 / 157

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

Сообщений: 1,246

02.05.2016, 20:07

3

nmcf, у ТС, скорее всего, создание класса Qt идет через множественное наследование, а не с помощью агрегации через указатель, а Ui::ChatDialog — форма дизайнера QtC



0



7533 / 6396 / 2916

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

Сообщений: 27,855

02.05.2016, 20:09

4

0x90h, так можно делать?



0



666 / 444 / 157

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

Сообщений: 1,246

02.05.2016, 20:11

5

Ошибка expected class-name before '{' token



0



7533 / 6396 / 2916

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

Сообщений: 27,855

02.05.2016, 20:14

6

Я не про множественное наследование, а про смешивание этих стандартных классов.



0



666 / 444 / 157

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

Сообщений: 1,246

02.05.2016, 20:15

7

смешивание? в смысле?



0



7533 / 6396 / 2916

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

Сообщений: 27,855

02.05.2016, 23:23

8

Не пойму, что там от чего наследуется. ChatDialog и Ui::ChatDialog — это разные классы?



0



666 / 444 / 157

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

Сообщений: 1,246

02.05.2016, 23:59

9



2



1 / 1 / 0

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

Сообщений: 197

03.05.2016, 21:09

 [ТС]

10

0x90h, ну так как ето исправить?

Добавлено через 22 секунды
nmcf, это один и тот же



0



666 / 444 / 157

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

Сообщений: 1,246

03.05.2016, 21:12

11

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

как ето исправить?

скрин ошибки покажите



0



1 / 1 / 0

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

Сообщений: 197

03.05.2016, 22:07

 [ТС]

12

0x90h, вот скрин



0



Wyn

1068 / 650 / 229

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

Сообщений: 2,031

Записей в блоге: 9

03.05.2016, 22:28

13

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

0x90h, вот скрин

А где у вас

C++ (Qt)
1
2
3
namespace Ui {
   class ChatDialog;
}

?

Добавлено через 2 минуты
Вообще всё как-то сделано через заднее место. Создайте новый проект с формой и посмотрите как вам автогенерация форму подключает.



0



0x90h

666 / 444 / 157

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

Сообщений: 1,246

03.05.2016, 22:59

14

Wyn,

C++ (Qt)
1
2
3
namespace Ui {
   class ChatDialog;
}

подобный код будет иметь место в хедере, если встраивание формы происходит при помощи агрегации через указатель, в случае ТС — класс создается множественным наследованием,

C++ (Qt)
1
class ChatDialog : public QDialog, private Ui::ChatDialog

как раз результат автогенерации, тут что-то другое, надо посмотреть весь код проекта



0



1 / 1 / 0

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

Сообщений: 197

04.05.2016, 10:09

 [ТС]

15

0x90h, вот весь проект



0



666 / 444 / 157

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

Сообщений: 1,246

04.05.2016, 10:26

16

Ошибка expected class-name before '{' token

у вас в форме chatdialog.ui почему-то менеджеры компоновки не имеют имен, если поправить, то ваш проект вполне нормально запускается



0



1 / 1 / 0

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

Сообщений: 197

04.05.2016, 10:28

 [ТС]

17

0x90h, не подскажите как это сделать…а то это второй проект в Qt



0



666 / 444 / 157

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

Сообщений: 1,246

04.05.2016, 10:33

18

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

Решение

откройте форму на редактирование, будет отображена форма, справа будет окошко инспектора объектов (это то, что показано на скриншоте выше), вот прямо по элементу с надписью «<без имени>» щелкните два раза мышкой и введите имя объекта (на английском)



1



1 / 1 / 0

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

Сообщений: 197

04.05.2016, 10:34

 [ТС]

19

0x90h, спасибо



0



666 / 444 / 157

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

Сообщений: 1,246

04.05.2016, 10:35

20

запустился проект?



0



This topic has been deleted. Only users with topic management privileges can see it.

  • Hey,
    I have built this class:

    #ifndef FUNCTIONNODE_H
    #define FUNCTIONNODE_H
    
    #include "node.h"
    
    class FunctionNode : public Node
    {}; //error here
    #endif // FUNCTIONNODE_H
    

    And get this error:

    error: expected class-name before '{' token
     {
     ^
    

    And I don’t know why. The class name is there, so the mistake is different to the error I think, but I got no other errors.
    Any ideas?
    Thanks for answers

  • are you sure it knows Node ?
    and its not node or anything like that ?

  • I added

    class Node;
    

    and now I get this:

     error: invalid use of incomplete type 'class Node'
     class FunctionNode : public Node
                                 ^
    

    Looks like you are right, it didn’t know class Node but I unfortunately don’t know what this really means… why is it incomplete type? Class Node is a QGraphicsItem derived class.

  • Hi

    this compiles fine here
    class TestNode{};
    class TestNodeChild : TestNode {
    };

    Incomplete means «Hey you only told me the class name»
    Nothing more.
    And that is not so good with inheritance as it needs to know base class ctor etc.

    When you do
    class node;
    That is a forward. And tells only name.
    It speed up compilation when allowed.
    The cure is full include
    #include «node.h»

  • @mrjj
    Ok… This is weird because I did include node.h . What does it need more?
    It has the class name and the header file. Is there a problem, that Node derives from QGraphicsItem or sth?

  • Hi,

    Can you also post the content of node.h

  • @Niagarer said in expected class-name error:

    Is there a problem, that Node derives from QGraphicsItem or sth?

    Nope.
    Unless the .h have some error that prevents parsing, then it should be fine.

    But as mr sgaist says, please show whole file so we can see if we spot it.

    I assume its not just because in .h file node and you use Node. (big vs small letters)

  • SOLUTION
    Yes, the problem was a bit bigger.

    Summarized:
    It was a problem with including other classes in the header files of the classes. The solution is, to use forward declaration ( class myClass; ) and include the myclass.h in the source (.cpp) file, not in the header file. I did not do this consequent and so, my derived class knew the parent class but thought, it would not have any content. Why, is good explained here (look to the answer post by Ben Voigt):
    https://stackoverflow.com/questions/5319906/error-expected-class-name-before-token

    Thanks for your help!!

    1. Default Expected class-name before ‘{‘ token

      I’ve working on my first project and I’ve hit a speed bump. When building, I get this error message. Expected class-name before ‘{‘ token in mainwindow.h line 8.

      Here is mainwindow.h:

      1. #ifndef MAINWINDOW_H

      2. #define MAINWINDOW_H

      3. #include "ui_mainwindow.h"

      4. class MainWindow : public QWidget, private Ui::MainWindowDLG

      5. {

      6. Q_OBJECT

      7. public:

      8. MainWindow(QWidget *parent = 0);

      9. public slots:

      10. void display_pic();

      11. };

      12. #endif

      To copy to clipboard, switch view to plain text mode 

      I know it’s got to be something simple I am overlooking. Thanks in advance.


    2. Default Re: Expected class-name before ‘{‘ token

      add #include <QWidget> in this file, e.g.

      1. #ifndef MAINWINDOW_H

      2. #define MAINWINDOW_H

      3. #include <QWidget>

      4. #include "ui_mainwindow.h"

      5. ...

      To copy to clipboard, switch view to plain text mode 

      Qt Assistant — rocks!
      please, use tags [CODE] & [/CODE].


    3. Default Re: Expected class-name before ‘{‘ token


    4. Default Re: Expected class-name before ‘{‘ token

      Qt Assistant — rocks!
      please, use tags [CODE] & [/CODE].


    5. Default Re: Expected class-name before ‘{‘ token

      Attached #include <QWidget> too all other files main.cpp, mainwindow.cpp, and mainwindow.h. I think that is what you wanted me to try. Still get the same error message.


    6. Default Re: Expected class-name before ‘{‘ token

      no, I was asking you to upload your sources, that I can try to compile your project by myself.

      Qt Assistant — rocks!
      please, use tags [CODE] & [/CODE].


    7. Default Re: Expected class-name before ‘{‘ token

      Sorry. Here we go…

      main.cpp

      1. #include <QApplication>

      2. #include "mainwindow.h"

      3. int main(int argc, char *argv[])

      4. {

      5. MainWindow *dialog = new MainWindow;

      6. dialog->show();

      7. return app.exec();

      8. }

      To copy to clipboard, switch view to plain text mode 

      mainwindow.cpp

      1. #include "mainwindow.h"

      2. #include <QtGui>

      3. #include <QPixmap>

      4. MainWindow::MainWindow(QWidget *parent)

      5. {

      6. setupUi(this);

      7. connect( pushButton_display, SIGNAL( clicked() ), this, SLOT( display_pic() ) );

      8. }

      9. void MainWindow::display_pic()

      10. {

      11. label_image->setPixmap(pixmap);

      12. }

      To copy to clipboard, switch view to plain text mode 

      mainwindow.h

      1. #ifndef MAINWINDOW_H

      2. #define MAINWINDOW_H

      3. #include <QWidget>

      4. #include "ui_mainwindow.h"

      5. class MainWindow : public QWidget, private Ui::MainWindowDLG

      6. {

      7. Q_OBJECT

      8. public:

      9. MainWindow(QWidget *parent = 0);

      10. public slots:

      11. void display_pic();

      12. };

      13. #endif

      To copy to clipboard, switch view to plain text mode 

      ui_mainwindow.h

      1. /********************************************************************************

      2. ** Form generated from reading ui file 'mainwindow.ui'

      3. **

      4. ** Created: Mon Jun 15 22:04:49 2009

      5. ** by: Qt User Interface Compiler version 4.5.1

      6. **

      7. ** WARNING! All changes made in this file will be lost when recompiling ui file!

      8. ********************************************************************************/

      9. #ifndef UI_MAINWINDOW_H

      10. #define UI_MAINWINDOW_H

      11. #include <QtCore/QVariant>

      12. #include <QtGui/QAction>

      13. #include <QtGui/QApplication>

      14. #include <QtGui/QButtonGroup>

      15. #include <QtGui/QHeaderView>

      16. #include <QtGui/QLabel>

      17. #include <QtGui/QMainWindow>

      18. #include <QtGui/QPushButton>

      19. #include <QtGui/QWidget>

      20. QT_BEGIN_NAMESPACE

      21. class Ui_MainWindow

      22. {

      23. public:

      24. {

      25. if (MainWindow->objectName().isEmpty())

      26. MainWindow->setObjectName(QString::fromUtf8("MainWindow"));

      27. MainWindow->resize(770, 524);

      28. MainWindow->setStyleSheet(QString::fromUtf8("background-color: rgb(136, 162, 255);n"

      29. ""));

      30. centralWidget = new QWidget(MainWindow);

      31. centralWidget->setObjectName(QString::fromUtf8("centralWidget"));

      32. label_image = new QLabel(centralWidget);

      33. label_image->setObjectName(QString::fromUtf8("label_image"));

      34. label_image->setGeometry(QRect(10, 10, 751, 461));

      35. label_image->setStyleSheet(QString::fromUtf8("background-color: rgba(62, 99, 255, 43);"));

      36. pushButton_display = new QPushButton(centralWidget);

      37. pushButton_display->setObjectName(QString::fromUtf8("pushButton_display"));

      38. pushButton_display->setGeometry(QRect(330, 480, 113, 32));

      39. MainWindow->setCentralWidget(centralWidget);

      40. retranslateUi(MainWindow);

      41. } // setupUi

      42. {

      43. MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));

      44. label_image->setText(QString());

      45. pushButton_display->setText(QApplication::translate("MainWindow", "Push Me", 0, QApplication::UnicodeUTF8));

      46. Q_UNUSED(MainWindow);

      47. } // retranslateUi

      48. };

      49. namespace Ui {

      50. class MainWindow: public Ui_MainWindow {};

      51. } // namespace Ui

      52. QT_END_NAMESPACE

      53. #endif // UI_MAINWINDOW_H

      To copy to clipboard, switch view to plain text mode 


    8. Default Re: Expected class-name before ‘{‘ token

      try this

      mainwindow.cpp

      1. #include "mainwindow.h"

      2. #include <QtGui>

      3. #include <QPixmap>

      4. MainWindow::MainWindow(QWidget *parent)

      5. {

      6. setupUi(this);

      7. connect( pushButton_display, SIGNAL( clicked() ), this, SLOT( display_pic() ) );

      8. }

      9. void MainWindow::display_pic()

      10. {

      11. label_image->setPixmap(pixmap);

      12. }

      To copy to clipboard, switch view to plain text mode 

      mainwindow.h

      1. #ifndef MAINWINDOW_H

      2. #define MAINWINDOW_H

      3. #include <QMainWindow>

      4. #include "ui_mainwindow.h"

      5. class MainWindow : public QMainWindow, private Ui::MainWindowDLG

      6. {

      7. Q_OBJECT

      8. public:

      9. MainWindow(QWidget *parent = 0);

      10. public slots:

      11. void display_pic();

      12. };

      13. #endif

      To copy to clipboard, switch view to plain text mode 

      Qt Assistant — rocks!
      please, use tags [CODE] & [/CODE].


    9. Default Re: Expected class-name before ‘{‘ token

      Quote Originally Posted by spirit
      View Post

      1. MainWindow::MainWindow(QWidget *parent)

      To copy to clipboard, switch view to plain text mode 

      Hi, a short side question. I pass everytime parent to the ctor of the base class. What’s the advantage of passing this?


    10. 15th June 2009, 21:03


      #10

      Default Re: Expected class-name before ‘{‘ token

      mistyped, of course must be passed parent.

      Qt Assistant — rocks!
      please, use tags [CODE] & [/CODE].


    11. 15th June 2009, 21:05


      #11

      Default Re: Expected class-name before ‘{‘ token

      Did you add the «mainwindow.ui» file to your project file and reran qmake? I guess you did… nevermind…

      Your biological and technological distinctiveness will be added to our own. Resistance is futile.

      Please ask Qt related questions on the forum and not using private messages or visitor messages.


    12. 15th June 2009, 21:13


      #12

      Default Re: Expected class-name before ‘{‘ token

      Quote Originally Posted by spirit
      View Post

      mistyped, of course must be passed parent.

      Fine, than I can stop thinking about


    13. 16th June 2009, 05:26


      #13


    14. 16th June 2009, 06:18


      #14

      Default Re: Expected class-name before ‘{‘ token

      ok, attach to your next post an archive with sources, pro-file and ui-file.

      Qt Assistant — rocks!
      please, use tags [CODE] & [/CODE].


    15. 16th June 2009, 08:43


      #15

      Default Re: Expected class-name before ‘{‘ token

      Are we blind or what?

      The class is called Ui::MainWindow, not Ui::MainWindowDLG!

      The line should say:

      1. class MainWindow : public QMainWindow, private Ui::MainWindow

      To copy to clipboard, switch view to plain text mode 

      Your biological and technological distinctiveness will be added to our own. Resistance is futile.

      Please ask Qt related questions on the forum and not using private messages or visitor messages.


    16. 16th June 2009, 09:48


      #16

      Default Re: Expected class-name before ‘{‘ token

      Quote Originally Posted by wysota
      View Post

      Are we blind or what?

      The class is called Ui::MainWindow, not Ui::MainWindowDLG!

      The line should say:

      1. class MainWindow : public QMainWindow, private Ui::MainWindow

      To copy to clipboard, switch view to plain text mode 

      damn, you are right!

      Qt Assistant — rocks!
      please, use tags [CODE] & [/CODE].


    17. 16th June 2009, 11:37


      #17

      Default Re: Expected class-name before ‘{‘ token

      That’s it! Builds without any problems. Of course when I try to run the program I get an error message and the program doesn’t start. «The application image_2 quit unexpectedly» And I got to ignore, report, or relaunch. I guess the fun is just beginning. Thanks for your help. I got a feeling I’ll be back.


    In this comprehensive guide, we will explore the ‘Expected Class-Name Before {‘ token error, which is a common error developers face while working with C++ code. We will discuss what this error means, what causes it, and how to fix it. By the end of this guide, you will be well-equipped to identify and resolve this error in your C++ projects.

    Table of Contents

    1. Understanding the ‘Expected Class-Name Before {‘ Token Error
    2. Common Causes of the Error
    3. Step-by-Step Guide to Fix the Error
    4. FAQs
    5. Related Resources

    Understanding the ‘Expected Class-Name Before {‘ Token Error

    The ‘Expected Class-Name Before {‘ token error occurs when the C++ compiler expects a class name before the opening brace ‘{‘ but does not find one. This error is a syntax error, which means that the compiler is unable to understand the code due to incorrect structure or grammar.

    Common Causes of the Error

    There are several reasons why this error might occur in your C++ code. Some of the most common causes include:

    Missing or incorrect class declaration: The error can occur when the class is not declared properly or the class declaration is missing altogether.

    Incorrect use of inheritance: If you are trying to inherit from a class but the syntax is incorrect, this error might pop up.

    Typographical errors: Sometimes, simple typos or incorrect capitalization can lead to this error.

    Step-by-Step Guide to Fix the Error

    Follow these steps to identify and fix the ‘Expected Class-Name Before {‘ token error in your C++ code:

    Inspect the class declaration: Check if the class declaration in your code is correct and follows the proper syntax. Make sure you have the class keyword followed by the class name and then the opening brace ‘{‘. For example:

    class MyClass {
        // Class definition
    };
    

    Check for inheritance issues: If you are using inheritance in your code, make sure you are using the correct syntax. The class being inherited should be placed after a colon : following the derived class’s name. For example:

    class DerivedClass : public BaseClass {
        // Class definition
    };
    

    Look for typographical errors: Double-check your code for any spelling mistakes, typos, or incorrect capitalization that might be causing the error.

    1. Check included header files: Make sure you have included the necessary header files and used the correct namespaces for the classes being used or inherited.

    If you have gone through these steps and the error persists, consider seeking help from a colleague or online forums, such as Stack Overflow.

    FAQs

    1. Is the ‘Expected Class-Name Before {‘ token error specific to C++?

    Yes, this error is specific to C++ as it relates to class declaration and inheritance, which are features of object-oriented programming languages like C++.

    2. Can this error occur in other object-oriented programming languages?

    While this specific error message might not appear in other languages, similar syntax errors can occur in languages like Java or C# if the class declaration or inheritance syntax is incorrect.

    3. What is the difference between a syntax error and a runtime error?

    A syntax error occurs when the compiler is unable to understand the code due to incorrect structure or grammar, whereas a runtime error occurs during the execution of the program when the code encounters an exceptional condition or an invalid operation.

    4. Can I use an Integrated Development Environment (IDE) to help me identify and fix this error?

    Yes, an IDE can be very helpful in identifying and fixing syntax errors like the ‘Expected Class-Name Before {‘ token error. Many IDEs provide real-time error checking and suggestions to fix the errors.

    5. Can I ignore this error if my code still compiles and runs?

    No, this error is a syntax error, which means that the compiler will not be able to compile your code until it is fixed.

    • C++ Classes and Objects: Learn more about C++ classes and objects, including class declaration and inheritance.
    • C++ Inheritance: A comprehensive tutorial on inheritance in C++.
    • C++ Programming/Error Handling: Learn more about error handling in C++ programming.

    Понравилась статья? Поделить с друзьями:
  • Qt кракозябры вместо ошибок
  • R01 ошибка на котле koreastar
  • Qt platform plugin windows ошибка как исправить
  • R01 ошибка на котле ferroli
  • Qt designer ошибка генерации кода