Error expected after class definition

I seriously have no idea what has gone wrong here. It would be nice if somebody could help.By the way I'm using Codeblocks. I was just trying to write a program using class but something seems out of

I seriously have no idea what has gone wrong here. It would be nice if somebody could help.By the way I’m using Codeblocks. I was just trying to write a program using class but something seems out of place. Any help would be appreciated.If u have any doubts just ask me in the comments.

#include <iostream>
using namespace std;
const int m = 50;

class ITEMS
{
    int itemcode[m];
    float itemprice[m];
    int count;
public:
    void CNT(void) { count = 0 };
    void getitem(void);
    void displaysum(void);
    void remove(void);
    void displayitems(void);
};

{
    cout << "Enter item code:";
    cin >> itemcode[count];
    cout << "Enter item cost:";
    cin >> itemprice[count];
    count++;
}

void ITEMS::displaysum(void)
{
    float sum = 0;
    for (int i < count; i++)
        sum = sum + itemprice[i];
    cout << "nTotal value:" << sum << "n";
}

void ITEMS::remove(void)
{
    int a;
    cout << "Enter item code:";
    cin >> a;
    for (int i = 0; i < count; i++)
        if (itemcode[i] == a)
            itemprice[i] = 0;
}

void ITEMS::displayitems(void)
{
    cout << "nCode Pricen";
    for (int i = 0; i < count; i++)
        {
        cout << "n" << itemcode[i];
        cout << " " << itemprice[i];
        }
    cout << "n";
}

int main()
{
    ITEMS order;
    order.CNT();
    int x;
    do
        {
        cout << "nYou can do the following";
        cout << "Enter appropriate number n";
        cout << "n1: Add an item";
        cout << "n2: Display total value";
        cout << "n3: Delete an item";
        cout << "n4: Display all items";
        cout << "n5: Quit";
        cin >> x;
        switch (x)
            {
            case 1:  order.getitem(); break;
            case 2: order.displaysum(); break;
            case 3: order.remove(); break;
            case 4: order.displayitems(); break;
            case 5: break;
            default: cout << "Error in input; try againn";
            }
        }
    while (x != 5);
    return 0;
}   

Error shown in compiler:

Error:||=== Build: Debug in C++ (compiler: GNU GCC Compiler) ===|
E:C++Member.cpp|15|error: expected ';' after class definition|
E:C++Member.cpp|16|error: expected unqualified-id before '{' token|
E:C++Member.cpp||In member function 'void ITEMS::displaysum()':|
E:C++Member.cpp|27|error: expected ';' before '<' token|
E:C++Member.cpp|27|error: expected primary-expression before '<' token|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

My desired output is:

 You can do the following; Enter appropriate number
 1:Add an Item
 2:Display total value
 3:Delete an Item
 4:Display all items
 5:Quit
 What is your option?1
 Enter item code :111
 Enter item cost :100
 You can do the following; Enter appropriate number
 1:Add an Item
 2:Display total value
 3:Delete an Item
 4:Display all Items
 5:Quit
 What is your option?!
 Enter Item code :222
 Enter Item cost :2DO
 You can do the following; Enter appropriate number
 1:Add an item
 2:Display total value
 3:Delete an item
 4:Display all items
 5:Quit
 What is your option?1
 Enter item code :333
 Enter item cost :300
 You can do the following; Enter appropriate number
 1:Add an Item
 2:Display total value
 3:Delete an Item 
 4:Display all Items
 5:Quit
 What is your option?2
 Total value :600
 You can do the following; Enter appropriate number
 1:Add an Item
 2:Display total value
 3:Delete an item
 4:Display all items
 5:Quit
 What is your option?3
 Enter Item code :222
 You can do the following; Enter appropriate number
 1:Add an item
 2:Display total value
 3:Delete an item
 4:Display all items
 5:Quit
 What is your option?4
 Code Price
  111 100
  222 0
  333 300
You can do the following; Enter appropriate number
1:Add an item
2:Display total value
3:Delete an item
4:Display all items
5:Quit
What is your option?5

Содержание

  1. Что означает «error: ‘.class’ expected» и как ее исправить
  2. 1 ответ
  3. Что означает сообщение об ошибке и что ее вызывает?
  4. Как это исправить?
  5. Еще примеры
  6. GCC Debugging/g++/Errors
  7. Contents
  8. abstract declarator ‘TYPE’ used as declaration [ edit | edit source ]
  9. call of overloaded ‘FUNCTION’ is ambiguous [ edit | edit source ]
  10. ‘VARIABLE’ cannot appear in a constant-expression [ edit | edit source ]
  11. ‘VARIABLE’ cannot be used as a function [ edit | edit source ]
  12. conversion from ‘TYPE’ to non-scalar type ‘TYPE’ requested [ edit | edit source ]
  13. could not convert ‘STATEMENT’ to ‘bool’ [ edit | edit source ]
  14. declaration of ‘FUNCTION’ outside of class is not definition [ edit | edit source ]
  15. declaration of ‘VARIABLE’ shadows a parameter [ edit | edit source ]
  16. ‘TYPE’ does not name a type [ edit | edit source ]
  17. expected ‘TOKEN’ before ‘TOKEN’ token [ edit | edit source ]
  18. expected primary-expression before ‘TOKEN’ [ edit | edit source ]
  19. expected unqualified-id before [ edit | edit source ]
  20. incompatible types in assignment of ‘TYPE’ to ‘TYPE’ [ edit | edit source ]
  21. invalid conversion from ‘TYPE’ to ‘TYPE’ [ edit | edit source ]
  22. invalid operands of types ‘TYPE’ and ‘TYPE’ to binary ‘FUNCTION’ [ edit | edit source ]
  23. invalid use of template-name [ edit | edit source ]
  24. is not a member of [ edit | edit source ]
  25. ‘TYPE’ is not a type [ edit | edit source ]
  26. ‘CLASS_MEMBER’ is private within this context [ edit | edit source ]
  27. Как исправить ошибку C ++: ожидаемый неквалифицированный идентификатор
  28. 6 ответов
  29. Error expected after class definition

Что означает «error: ‘.class’ expected» и как ее исправить

Иногда новые пользователи сталкиваются со следующей довольно неясной ошибкой компиляции ‘.class’ expected :

Некоторые компиляторы Java IDE заявляют об этом несколько иначе; например,

Что означают такие ошибки на самом деле , что их вызывает и как их исправить?

1 ответ

Прежде всего, это ошибка компиляции. Если вы видите это сообщение в времени выполнения , вероятно, вы выполняете код с ошибками компиляции.

Вот пара примеров ошибки:

В обоих случаях сообщение об ошибке компилятора будет error: ‘.class’ expected .

Что означает сообщение об ошибке и что ее вызывает?

Компилятор запутался во время проверки синтаксиса из-за некоторого (откровенно говоря) бессмысленного кода. Компилятор обнаружил тип (например, int или int[] ) в контексте, в котором он фактически ожидал выражение. Затем говорится, что единственными синтаксически приемлемыми символами на данном этапе будут . , за которым следует class .

Вот пример правильного синтаксиса;

Примечание. Всегда должно быть возможно выяснить, почему средство проверки синтаксиса компилятора считает, что тип должен быть выражением. Однако часто проще рассматривать это как «компилятор сбит с толку» и искать (неизбежную!) Синтаксическую ошибку, которая вызвала путаницу. Эта синтаксическая ошибка может быть неочевидной . для новичка . но знание того, что это основная причина, — хорошее начало.

Как это исправить?

К сожалению, «предложение» добавить .class почти всегда неверно. Это, конечно, не поможет в двух примерах в начале этого ответа!

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

Если вы намеревались написать приведение типа , вам нужно заключить тип в круглые скобки; например

Если вы просто намеревались присвоить значение или передать параметр как есть, то этот тип следует удалить.

При объявлении метода необходимо указать тип формального параметра . Но обычно вам не нужно указывать его для фактического аргумента . В тех редких случаях, когда вы это делаете (чтобы разрешить неоднозначность перегрузки), вы используете приведение типа.

Еще примеры

Об ошибке сообщается на array[] , потому что это тип, а не выражение. Исправление, вероятно, будет либо:

Программист поместил объявление параметра в вызов метода. Здесь требуется выражение, а не объявление:

Программист пытался выполнить приведение типов. Это должно быть написано так:

Программист добавил ложную точку с запятой. Это должно быть написано так:

someArray[] обозначает тип, а не выражение. Программист, вероятно, имеет в виду что-то вроде someArray[someIndex] > 80 или someArray.length > 80 .

integers[] обозначает декларатор типа, но выражение является обязательным. Это должно быть либо

Ошибка здесь в том, что в операторах «then» должны быть фигурные скобки.

Но замешательство компилятора состоит в том, что предложение then в if не может быть объявлением переменной. Итак, синтаксический анализатор ищет выражение, которое могло бы быть вызовом метода. Например, локально синтаксически допустимым будет следующее:

. хотя и бессмысленный с точки зрения того, что он пытается делать. И, конечно же, компилятор перехватит висящий else .

Источник

GCC Debugging/g++/Errors

Contents

abstract declarator ‘TYPE’ used as declaration [ edit | edit source ]

  • Message found in GCC version 4.5.1
    • often grouped together with:
      • member ‘DATA_MEMBER’ with constructor not allowed in anonymous aggregate
      • member ‘DATA_MEMBER’ with destructor not allowed in anonymous aggregate
      • member ‘DATA_MEMBER’ with copy assignment operator not allowed in anonymous aggregate
  • a class or struct is missing a name:
  • a header file has a class or struct with a name already used inside ifndef, define statements

call of overloaded ‘FUNCTION’ is ambiguous [ edit | edit source ]

‘VARIABLE’ cannot appear in a constant-expression [ edit | edit source ]

‘VARIABLE’ cannot be used as a function [ edit | edit source ]

  • Message found in GCC version 4.5.1
  • make sure the variable name does not have an underscore in it (compiler weirdness)
  • you’re using the same name for a variable name and a function inside a function definition

conversion from ‘TYPE’ to non-scalar type ‘TYPE’ requested [ edit | edit source ]

  • Message found in GCC version 4.5.1
  • type conversion error, look for missing «::» syntax or missing parenthesis
  • possibly a casting error
  • a class member function returns a value that does not match the function’s declared return type

could not convert ‘STATEMENT’ to ‘bool’ [ edit | edit source ]

  • Message found in GCC versions 3.2.3, 4.5.1
  • you a mistyped comparison operator (e.g., using: «=» instead of «==»)
  • you used an incorrect return type for the called function’s definition
  • you’re using an invalid argument for a conditional statement

declaration of ‘FUNCTION’ outside of class is not definition [ edit | edit source ]

  • Message found in GCC versions 3.2.3, 4.5.1
  • try using ‘=’ to initialize a value instead of parenthesis
  • you used a semicolon or comma between a constructor and an initializer list instead of a colon
  • you left a semicolon before the body of a function definition

declaration of ‘VARIABLE’ shadows a parameter [ edit | edit source ]

  • Message found in GCC versions 3.2.3, 4.5.1
  • you’re redefining a variable name that’s already in use, possibly declared in the function’s parameter list

‘TYPE’ does not name a type [ edit | edit source ]

  • Message found in GCC version 4.5.1
    • in GCC version 3.2.3 sometimes reported as: syntax error before ‘CHARACTER’ token
    • in GCC version 4.0.1, sometimes reported as: ISO C++ forbids declaration
      • e.g.: ISO C++ forbids declaration of ‘vector’ with no type
  • you left out an object’s name qualifier or using directive
  • make sure you didn’t mistype the scope operator «::», e.g.: «name:name» instead of «name::name»
  • make sure you included the required libraries
  • a header file is listed after a file that makes use of it in the include directives

expected ‘TOKEN’ before ‘TOKEN’ token [ edit | edit source ]

  • Message found in GCC versions 3.2.3, 4.5.1
    • in GCC version 3.2.3 sometimes reported as: syntax error before ‘CHARACTER’ token
  • check for a missing comma or parenthesis in a function’s parameters
  • check for a missing semicolon
    • e.g.: expected ‘,’ or ‘;’ before ‘TOKEN’
  • possibly from a double namespace definition, or a fully-qualified (e.g., std::cout) name already under a ‘using’ directive
  • possible missing ‘ >’ operator in a cin/cout statement

expected primary-expression before ‘TOKEN’ [ edit | edit source ]

expected unqualified-id before [ edit | edit source ]

  • Message found in GCC version 4.5.1
  • check your syntax for missing, misplaced, or erroneous characters
  • expected unqualified-id before ‘(‘ token
    • e.g.: parentheses in a class name
  • expected unqualified-id before ‘return’
    • e.g.: missing opening brace in a conditional statement

incompatible types in assignment of ‘TYPE’ to ‘TYPE’ [ edit | edit source ]

  • Message found in GCC versions 4.5.1
  • you’re trying to assign to or initialize a character array using a character pointer
    • e.g.: incompatible types in assignment of ‘const char*’ to ‘char [10]’
  • improperly accessing elements of a 2D array

invalid conversion from ‘TYPE’ to ‘TYPE’ [ edit | edit source ]

  • Message found in GCC versions 3.2.3, 4.5.1
  • make sure parentheses were not left out of a function name
  • make sure you are passing a function the correct arguments

invalid operands of types ‘TYPE’ and ‘TYPE’ to binary ‘FUNCTION’ [ edit | edit source ]

  • Message found in GCC version 4.5.1
  • You’re trying to concatenate to C string arguments with the addition operator

invalid use of template-name [ edit | edit source ]

is not a member of [ edit | edit source ]

  • Message found in GCC versions 4.5.1
  • check for a missing header include

example: ‘cout’ is not a member of ‘std’

‘TYPE’ is not a type [ edit | edit source ]

  • Message found in GCC version 4.5.1
    • in GCC version 3.2.3 reported as: type specifier omitted for parameter ‘PARAMETER’
  • you mistyped a template parameter in a function declaration
  • an included header file does not have the correct libraries included in the source file to implement it:
    • e.g.: you’re using #include «bar.h» without including the «foo.h» that «bar.h» needs to work
  • Check that there are no methods with the same name as ‘TYPE’.

‘CLASS_MEMBER’ is private within this context [ edit | edit source ]

  • Message found in GCC versions 3.2.3, 4.5.1
  • usually reported in the format:
    • (LOCATION_OF_PRIVATE_DATA_MEMBER) error: ‘DATA_MEMBER’ is private
    • (LOCATION_OF_CODE_ACCESSING_PRIVATE_DATA) error: within this context
  • Message usually results from trying to access a private data member of a class or struct outside that class’s or struct’s definition
  • Make sure a friend member function name is not misspelled
  • make sure a read only function is using a ‘const’ argument type for the class
  • make sure functions that alter data members are not const
  • check for derived class constructors implicitly accessing private members of base classes

possible fix, assign the whole object rather than part of it:

Источник

Как исправить ошибку C ++: ожидаемый неквалифицированный идентификатор

Я получаю эту ошибку в строке 6:

Я не могу сказать, что случилось.

6 ответов

Здесь не должно быть точки с запятой:

. но он должен быть в конце определения вашего класса:

Как бы то ни было, у меня была та же проблема, но не из-за лишней точки с запятой, а из-за того, что я забыл точку с запятой в предыдущем операторе.

Моя ситуация была примерно такой

Из этого кода мой компилятор все время говорил мне:

Для всех, кто столкнулся с такой ситуацией: я увидел эту ошибку, когда случайно использовал my_first_scope::my_second_scope::true вместо простого true , например:

Это потому, что у меня был макрос, из-за которого MY_MACRO(true) по ошибке расширился до my_first_scope::my_second_scope::true , и я действительно звонил bool my_var = MY_MACRO(true); .

Вот краткая демонстрация этого типа ошибки определения объема:

Программа (вы можете запустить ее онлайн здесь: https://onlinegdb.com/BkhFBoqUw):

Вывод (ошибка сборки):

Обратите внимание на ошибку: error: expected unqualified-id before ‘true’ , и куда указывает стрелка под ошибкой. Очевидно, «unqualified-id» в моем случае — это оператор области видимости с двойным двоеточием ( :: ), который у меня есть непосредственно перед true .

Когда я добавляю макрос и использую его (запустите этот новый код здесь: https://onlinegdb.com/H1eevs58D ):

Вместо этого я получаю новую ошибку:

В качестве побочного примечания рассмотрите возможность передачи строк в setWord () как константных ссылок, чтобы избежать избыточного копирования. Кроме того, в displayWord подумайте о том, чтобы сделать эту функцию константной, чтобы она соответствовала константной корректности.

Избавьтесь от точки с запятой после WordGame .

Вы действительно должны были обнаружить эту проблему, когда класс был намного меньше. Когда вы пишете код, вы должны компилировать каждый раз, когда добавляете полдюжины строк.

Точка с запятой должна стоять в конце определения класса, а не после имени:

Источник

Error expected after class definition

I’ve encountered another problem whilst trying to compile a fairly large codebase(about 20 classes). I’m getting the following compiler-error:

This is the problematic code:

Since there are quite a lot of files, I’m not expecting there to be a straight forward solution to this, but how would I go about finding a solution to this? If someone could point me in the right direction, I would be very grateful;)

I think all that should be covered, but if you would care to take a look, here’s the GeometricObject class

You might want to check to make sure you have not defined __GEOMETRICOBJECT__ in another file by accident (copy/paste?) since doing so would skip your definition of GeometricObject. The compiler doesn’t seem to think GeometricObject is a class name. Your declaration of Sphere looks correct, so I would guess that the problem is with the base class.

Ok, I checked that now, and it seems fine, I cant see any definitions of __GEOMETRICOBJECT__ anywhere else. I realize now that I forgot to include the full compiler error, maybe that could help:

Ok, here is what happens:
* GeometricObject.cpp includes GeometricObject.h in order to get the definition for class GeometricObject
* GeometricObject.h includes ShadeRec.h in order to get the definition of ShadeRec. Notice that at this point GeometricObject is not defined yet.
* some other include stuff along the chain
* Sphere.h tries to include GeometricObject.h, but the guarding token __GEOMETRICOBJECT__ has been already defined and nothing happens
* class Sphere tries to derive from Geometric object, but it still has no definition. It will later, after the preprocessor returns from the ShadeRec.h include inside GeometricObject.h, but this is no use at this point

What can you do?
You can use forward declaration as you have used already in some places. Such declaration tells the compiler that you know a certain class is defined somewhere, but you disclose nothing yet about its interface and members.

You can not do this:

, because this is inheritance, and the forward declaration provides no information on the size of the GeometricObject class, nor on the interface.

But you can do this:

, because GeometricObject only refers to ShadeRec, it does not contain ShadeRec objects as member variables and doesn’t inherit from the ShadeRec class.

It is impossible to have mutual containment, like A contains/derives from B, and B contains/derives from A. This would create infinite recursion between the definitions of those two classes.

Источник

  • Forum
  • Beginners
  • Including a Header file, does not compil

Including a Header file, does not compile

you are missing a ;
in carddeck.h

If you want us to look at the code, post your code with code tags.

I tried putting it in the body paragraph but it’s a huge code and it exceeded the max number of characters. and I tried it and it gave me another error

C:UsersjohndoeDocumentsUntitled2.cpp In file included from C:UsersjohndoeDocumentsUntitled2.cpp

C:UsersjohndoeDocumentscarddeck.h [Error] expected ‘;’ after class definition

Last edited on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class carddeck
{
private:
	const int DECKSIZE;
	int cardDeck[52];

public:
	carddeck();

	void displayCard(int card);

	int getCardValue(int card);

	void shuffleCards();

	int dealCard();
};

This is my header file

Last edited on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class carddeck
{
private:
	const int DECKSIZE;
	int cardDeck[52];

public:
	carddeck();

	void displayCard(int card);

	int getCardValue(int card);

	void shuffleCards();

	int dealCard();
};

This is my header file

Sorry, it isn’t.
In the version you uploaded on Dropbox the last semicolon is missing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class carddeck
{
private:
	const int DECKSIZE;
	int cardDeck[52];

public:
	carddeck();

	void displayCard(int card);

	int getCardValue(int card);

	void shuffleCards();

	int dealCard();
} // <-- a semicolon is missing here 

The compiler also complains for other errors and warnings:

In file included from carddeckimplementation.cpp:2:0:
carddeck.h:17:2: error: expected ';' after class definition
 }
  ^
  ;
carddeckimplementation.cpp: In constructor 'carddeck::carddeck()':
carddeckimplementation.cpp:7:1: error: uninitialized const member in 'const int' [-fpermissive]
 carddeck::carddeck()
 ^~~~~~~~
In file included from carddeckimplementation.cpp:2:0:
carddeck.h:4:12: note: 'const int carddeck::DECKSIZE' should be initialized
  const int DECKSIZE;
            ^~~~~~~~
carddeckimplementation.cpp: In member function 'void carddeck::displayCard(int)':
carddeckimplementation.cpp:71:2: error: expected ';' before '}' token
  } //end switch
  ^
In file included from DiceMenu_wCards_vOOD.cpp:6:0:
carddeck.h:17:2: error: expected ';' after class definition
 }
  ^
  ;
DiceMenu_wCards_vOOD.cpp: In function 'void cardDeck()':
DiceMenu_wCards_vOOD.cpp:244:6: warning: unused variable 'value' [-Wunused-variable]
  int value;
      ^~~~~
DiceMenu_wCards_vOOD.cpp: In function 'void twentyone()':
DiceMenu_wCards_vOOD.cpp:593:5: warning: suggest explicit braces to avoid ambiguous 'else' [-Wdangling-else]
  if (winner == "")
     ^
DiceMenu_wCards_vOOD.cpp: In function 'void twentyone_V2()':
DiceMenu_wCards_vOOD.cpp:763:5: warning: suggest explicit braces to avoid ambiguous 'else' [-Wdangling-else]
  if (winner == "")
     ^
DiceMenu_wCards_vOOD.cpp:608:55: warning: unused variable 'mydeck' [-Wunused-variable]
  int playerOneHand[HANDSIZE], computerHand[HANDSIZE], mydeck[DECKSIZE] = { -5 };
                                                       ^~~~~~

Topic archived. No new replies allowed.

Я пытался сделать БПФ с помощью wxwidgets в Linux, но я не очень хорошо знаком с С++. Я пробовал два подхода, оба безуспешно, и я читал все об ошибках, ища похожие проблемы, и я до сих пор не понимаю, что не так.

Первый подход (все внутри класса)

#include <valarray>
#include <complex>
#include <sstream>
#include <iterator>
#include <vector>

class do_fft
{
public:
    typedef std::complex<double> Complex;
    typedef std::valarray<Complex> CArray;
        do_fft();
        virtual ~do_fft();
private:
    const static double PI = 3.141592653589793238460;
    CArray x;
    void setDados(CArray v)
    {
        CArray x = v;
    }
    CArray getFFT()
    {

        void fft(CArray& x)
        {  //line 27
            const size_t N = x.size();
            if (N <= 1) return;

            // divide
            CArray par = x[std::slice(0, N/2, 2)];
            CArray  impar = x[std::slice(1, N/2, 2)];

            // conquistar
            fft(par);
            fft(impar);

            // combinar
            for (size_t k = 0; k < N/2; ++k)
            {
                Complex t = std::polar(1.0, -2 * PI * k / N) * impar[k];
                x[k    ] = par[k] + t;
                x[k+N/2] = par[k] - t;
            }
        }
        fft(x);
        return x;
    } //line 49
} fftd; 

Ошибки при попытке компиляции:

do_fft.h|49|error: expected ‘;’ after
class definition| do_fft.h||In member function ‘do_fft::CArray
do_fft::getFFT()’:| do_fft.h|27|error: a function-definition is not
allowed here before ‘{’ token| do_fft.h|49|error: expected ‘}’ at end
of input| do_fft.h|49|warning: no return statement in function
returning non-void

Второй подход — Отдельные объявления от методов:

class do_fft
{
public:
    typedef std::complex<double> Complex;
    typedef std::valarray<Complex> CArray;
    //    do_fft();
    //    virtual ~do_fft();
private:
    const static double PI = 3.141592653589793238460;
    CArray x;
    void setDados(CArray v);
    CArray getFFT();
} fftd;


do_fft.cpp|3|error: ISO C++ forbids declaration of ‘setDados’ with no type [-fpermissive]| 
do_fft.cpp|3|error: prototype for ‘int do_fft::setDados(do_fft::CArray)’ does not match any in class ‘do_fft’| 
do_fft.h|19|error: candidate is: void do_fft::setDados(do_fft::CArray)| do_fft.cpp|8|error: ‘getFFT’ in ‘class do_fft’ does not name a type| ||=== Build finished: 4 errors, 0 warnings ===|

Мой вопрос: какие понятия что я бездельничаю и что будет правильный путь справиться с этим?

РЕДАКТИРОВАТЬ: Другой вопрос-> что делает «виртуальный ~do_fft();» эта линия? (среда IDE вставила его при создании класса)

Theaska

0 / 0 / 0

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

Сообщений: 9

1

15.05.2017, 21:31. Показов 4854. Ответов 4

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


C:testsort_classes_2.h:6: ошибка: expected class-name before ‘{‘ token
class sort_vector : public sort_classes{

sort_classes.h

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef SORT_CLASSES_H
#define SORT_CLASSES_H
#pragma once
#include <string>
#include <vector>
using namespace std;
template <class SortIterator, class classort>
class sort_classes{
public:
    sort_classes()=0;
    void shell_sort(SortIterator begin, SortIterator end);
    void rand_int();
    void rand_float();
    void rand_string();
protected:
    int n_size;
};
#endif // SORT_CLASSES_H

sort_classes_2.h

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef SORT_CLASSES_2_H
#define SORT_CLASSES_2_H
#pragma once
#include "sort_classes.h"
template <class classort>
class sort_vector : public sort_classes{
public:
    sort_vector(classort, int n);
protected:
    vector <classort> v;
};
 
#endif // SORT_CLASSES_2_H

sort_classes.cpp

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef SORT_CLASSES_CPP
#define SORT_CLASSES_CPP
#include "sort_classes_2.h"
#include <typeinfo>
template <class classort>
sort_vector <classort>::sort_vector(classort cs, int n)
{
    this->n_size=n;
    if (typeid(cs).name()=="int");
 
 
}
 
 
 
#endif // SORT_CLASSES_CPP

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



0



3 / 3 / 6

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

Сообщений: 25

15.05.2017, 21:34

2

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

};

17 строчка в sort_classes.h
11 строчка sort_classes_2.h

Убери «;»



0



0 / 0 / 0

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

Сообщений: 9

15.05.2017, 21:35

 [ТС]

3

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

Убери «;»

C:testsort_classes.h:17: ошибка: expected ‘;’ after class definition
}

C:testsort_classes_2.h:11: ошибка: expected ‘;’ after class definition
}



0



zss

Модератор

Эксперт С++

12641 / 10135 / 6102

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

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

15.05.2017, 21:46

4

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

Решение

C++
1
2
3
4
5
6
7
template <class SortIterator,class classort>
class sort_vector : public sort_classes<SortIterator,classort>{
public:
    sort_vector(classort, int n);
protected:
    vector <classort> v;
};
C++
1
2
3
4
5
6
template <class SortIterator,class classort>
sort_vector <SortIterator,classort>::sort_vector(classort cs, int n)
{
    this->n_size=n;
    if (typeid(cs).name()=="int");
}



1



0 / 0 / 0

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

Сообщений: 9

15.05.2017, 21:58

 [ТС]

5

Спасибо большое!



0




Recommended Answers

Your probably missing a semi-colon in the other file.

Jump to Post

It is understood that you are asking about an issue in your *.h file and that there are no #includes above this class’ definition. gerard is asking you about your *.cpp files. With an error like this, the cause of the problem frequently is not actually in the file that …

Jump to Post

In your *.h file, you don’t even need Line 6. Either remove the line or comment it out. Since C/C++ is case-sensitive, it doesn’t match anything anyway because your capitalization is wrong.

In your *.cpp file, move your #includes up to Lines 2 and 3, then move «using namespace …

Jump to Post

All 12 Replies

Member Avatar

12 Years Ago

Your probably missing a semi-colon in the other file.

Member Avatar


getack

12 Years Ago

But what other file? Foo is not including anything above itself? That’s the problem I’m having. If I put a «using namespace std» above the class declaration, i have to move the semicolon to before the using…

Member Avatar


Fbody

682



Posting Maven



Featured Poster


12 Years Ago

It is understood that you are asking about an issue in your *.h file and that there are no #includes above this class’ definition. gerard is asking you about your *.cpp files. With an error like this, the cause of the problem frequently is not actually in the file that the error reports it in, but rather a different linked file. Please post your *.cpp file.

Edited

12 Years Ago
by Fbody because:

n/a

Member Avatar


getack

12 Years Ago

Okay here is the code:

//LegalMoveChecker.h
#ifndef LEGALMOVECHECKER_H
#define LEGALMOVECHECKER_H

#include <iostream>
class legalFootSoldierMoveChecker;

class LegalMoveChecker
{
  public:
    virtual bool isThisALegalMove(int iCX, int iCY, int iDX, int iDY) = 0;
};

class LegalFootSoldierMoveChecker: public LegalMoveChecker
{
  public:
    bool isThisALegalMove(int iCX, int iCY, int iDX, int iDY);
};
#endif
//LegalFootSoldierMoveChecker.C
using namespace std;
#include <iostream>
#include "LegalMoveChecker.h"
bool LegalFootSoldierMoveChecker::isThisALegalMove(int iCX, int iCY, int iDX, int iDY)
{
	return true;
}

I get the error in line 6

Member Avatar


Fbody

682



Posting Maven



Featured Poster


12 Years Ago

In your *.h file, you don’t even need Line 6. Either remove the line or comment it out. Since C/C++ is case-sensitive, it doesn’t match anything anyway because your capitalization is wrong.

In your *.cpp file, move your #includes up to Lines 2 and 3, then move «using namespace std;» down to line 4.

Edited

12 Years Ago
by Fbody because:

n/a

Member Avatar


getack

12 Years Ago

Thanks for showing my capitalization mistake *embarrassed*

I did what you recommended and it still complaining about a missing semicolon before «class» in line 8

Member Avatar


Fbody

682



Posting Maven



Featured Poster


12 Years Ago

Are you sure the error is in this header file? Please paste a direct copy of the error you are getting.

Member Avatar


getack

12 Years Ago

Morning!

Here is the direct output copied from Terminal: I am using G++ to compile, and developing on a Linux platform.

In file included from Piece.C:11:
LegalMoveChecker.h:16: error: expected `;' before ‘class’
make: *** [FootSoldierPiece.o] Error 1

Just so you understand, I am working on a chess like game. This part is designed to check whether the user has requested a move that is legal for each specific type of piece. At this stage it only returns true, as I have not implemented the actual test logic yet.

Member Avatar


Fbody

682



Posting Maven



Featured Poster


12 Years Ago

This error is flagging the inclusion of LegalMoveChecker.h from Piece.C. I think you need to post the code of Piece.C for us to look at.

You mentioned that you’re using G++, but I don’t remember seeing what OS and IDE you’re using.

>>Just so you understand, I am working on a chess like game.
I figured it was something like that…

Edited

12 Years Ago
by Fbody because:

n/a

Member Avatar


getack

12 Years Ago

here is Piece.C

The OS I’m using is some ancient Debian at the university labs. Not sure about the version. I don’t use an IDE, I code in Kate and use make and terminal to build.

#include <iostream>
#include <cstring>
using namespace std;

#include "LegalMoveChecker.h"
#include "Piece.h"

void Piece::move(int iCX, int iCY, int iDX, int iDY)
{
	if(checkValidMove(iDX, iDY))
	{
		myPositionX = iDX;
		myPositionY = iDY;
	}
	else
	{
		throw "INVALID MOVE";
	}
}

bool Piece::checkValidMove(int iDX, int iDY)
{
	bool retVal;
	retVal = checker->isThisALegalMove(myPositionX, myPositionY, iDX, iDY);
	return retVal;
}

void Piece::makeSelected()
{
	iAmSelected = true;
}

Member Avatar


getack

12 Years Ago

These errors are making me crazier by the minute. I use a vector in my game somewhere, so I included <vector> in one of my .C files. The compiler now spits out a missing semicolon in stl_construct.h! But when I move the #include to the bottom the list of includes, the problem goes away. All my classes end with a semicolon. I hexaChecked. I swear.

Member Avatar

12 Years Ago

You could try compiling with the -E switch which informs the GCC compile to run the preprocessor only.

G++ filename -E -o resultfile

Note the file produced is large.


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Hi @bvanneerven, thanks for reporting this. I followed the steps and both codes for Auth is working. I was able to run the app by using this snippet:

import React, { useEffect } from 'react';
import { browserLocalPersistence, initializeAuth, onAuthStateChanged} from 'firebase/auth';
import { initializeApp} from 'firebase/app'
function App() {
  let firebaseApp;
  let firebaseAuth;

  useEffect(() => {
    let firebaseConfig = {
      apiKey: "",
      authDomain: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: "",
      appId: "",
      measurementId: ""
    };
    firebaseApp = initializeApp(firebaseConfig);    
    firebaseAuth = initializeAuth(firebaseApp,{persistence: browserLocalPersistence});

    onAuthStateChanged(firebaseAuth, (user) => {
      console.log('user', user);
      if (user) {
        // User is signed in, see docs for a list of available properties
        // https://firebase.google.com/docs/reference/js/firebase.User
        const uid = user.uid;
        console.log("User is signed in");
      } else {
        // User is signed out
        console.log("User is signed out");
      }
    });
  }, []);
}

Let me know if you’re still experiencing the issue.

Понравилась статья? Поделить с друзьями:
  • Error expected primary expression before const
  • Error expect received toequal expected deep equality
  • Error expected primary expression before char
  • Error exp was not declared in this scope
  • Error exiting jvm with code 1 org apache zookeeper util serviceutils