Error expected unqualified id before delete

C++:expected unqualified-id Сегодня услышал, что в терминах С++ структура похожа на класс, и может иметь конструкторыдеструкторы. Попробовал: struct some_struct_in_memoryСегодня услышал, что в терминах С++ структура похожа на класс, и может иметь конструкторыдеструкторы. Тогда это будет не структура а класс с дефолтным public доступом и дефолтным public наследованием. Если есть желание сохранить хоть немного единообразия […]

Содержание

  1. C++:expected unqualified-id
  2. Re: C++:expected unqualified-id
  3. Re: C++:expected unqualified-id
  4. Re: C++:expected unqualified-id
  5. Re: C++:expected unqualified-id
  6. Re: C++:expected unqualified-id
  7. Re: C++:expected unqualified-id
  8. Re: C++:expected unqualified-id
  9. Re: C++:expected unqualified-id
  10. Re: C++:expected unqualified-id
  11. Re: C++:expected unqualified-id
  12. Re: C++:expected unqualified-id
  13. Re: C++:expected unqualified-id
  14. Re: C++:expected unqualified-id
  15. Re: C++:expected unqualified-id
  16. Re: C++:expected unqualified-id
  17. Re: C++:expected unqualified-id
  18. Re: C++:expected unqualified-id
  19. Re: C++:expected unqualified-id
  20. Re: C++:expected unqualified-id
  21. Re: C++:expected unqualified-id
  22. Re: C++:expected unqualified-id
  23. Re: C++:expected unqualified-id
  24. Re: C++:expected unqualified-id
  25. Re: C++:expected unqualified-id
  26. Re: C++:expected unqualified-id
  27. [offtopic] Про жизнь.
  28. Re: [offtopic] Про жизнь.
  29. Re: [offtopic] Про жизнь.
  30. Re: [offtopic] Про жизнь.
  31. Как исправить ошибку C ++: ожидаемый неквалифицированный идентификатор
  32. 6 ответов
  33. C++- Help (error: expected unqualified-id before ‘return’)
  34. 2 Answers 2
  35. Related
  36. Hot Network Questions
  37. Subscribe to RSS
  38. Error: expected unqualified-id before ‘<‘ token < [closed]
  39. 2 Answers 2

C++:expected unqualified-id

Сегодня услышал, что в терминах С++ структура похожа на класс, и может иметь конструкторыдеструкторы. Попробовал:
struct some_struct_in_memory<

Получаю от gcc:
error: expected unqualified-id before «void»
error: expected `)’ before «void»

Что это такое и как с этим бороться?

Re: C++:expected unqualified-id

Либо помести обьявление внутрь обьявления структуры, либо обьяви

Re: C++:expected unqualified-id

С классом у тебя то же самое было бы.

так нужно писать только внутри объявления структуры.

А вне ее нужно писать

Re: C++:expected unqualified-id

Структура не просто похожа на класс. Это и есть класс с единтсвенным отличием: доступ по умолчанию public.

Re: C++:expected unqualified-id

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

Re: C++:expected unqualified-id

>Сегодня услышал, что в терминах С++ структура похожа на класс, и может иметь конструкторыдеструкторы.

Тогда это будет не структура а класс с дефолтным public доступом и дефолтным public наследованием. Если есть желание сохранить хоть немного единообразия в С++ проекте используй везде class, а struct делай в стиле Си для интероперабельности с Си кодом.

Re: C++:expected unqualified-id

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

Они все дали неправильные ответы.

Re: C++:expected unqualified-id

> Они все дали неправильные ответы.

не неправильные, а идеологически невыдержанные

Re: C++:expected unqualified-id

Почему неверные? То что структура С++ задумывалось для совместимости не маешает ей быть классом.

Re: C++:expected unqualified-id

>Почему неверные? То что структура С++ задумывалось для совместимости

Для совместимости с чем? Если она не POD, то она не совместимая

>не маешает ей быть классом

А какой смысл дублировать сущность? Неужели ради того чтобы один раз public не написать?

Re: C++:expected unqualified-id

На сколько я понимаю введено для совместимости c сишными структурами.

Re: C++:expected unqualified-id

Так что же неверно в выше написаном?

Re: C++:expected unqualified-id

Дело в том, что эта структура пишется в заmmapенную память, которая позже скидывается на диск. Эта структура — суперблок, так что мне бы не хотелось засорять плюсовыми прибамбасами образ диска 🙂

Re: C++:expected unqualified-id

>На сколько я понимаю введено для совместимости c сишными структурами.

Структура с конструктором/деструктором по С++ стандарту Plain Old Data (POD) не является и с сишными структурами может быть совместима только случайно.

Re: C++:expected unqualified-id

>Дело в том, что эта структура пишется в заmmapенную память, которая позже скидывается на диск. Эта структура — суперблок, так что мне бы не хотелось засорять плюсовыми прибамбасами образ диска 🙂

Делай методы init()/destroy(). У POD могут быть невиртуальные методы.

Re: C++:expected unqualified-id

значит без пользовательского ктора надо. Иначе она уже не под.

Re: C++:expected unqualified-id

> Структура с конструктором/деструктором по С++ стандарту Plain Old Data (POD) не является и с сишными структурами может быть совместима только случайно.

уточнение: если конструктор без деструктора, то POD:

A POD-struct is an aggregate class that has no non-static data members of type pointer to member, non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor.

Re: C++:expected unqualified-id

> Дело в том, что эта структура пишется в заmmapенную память, которая позже
> скидывается на диск. Эта структура — суперблок,

А вот за это пороть нужно. Что будет, если такую чудо-ФС перенесут с 32-битной
машины на 64-битную? С little endian машины на big endian?

Re: C++:expected unqualified-id

Простите меня заранее. Пишется оно под 64 бита. Под встраиваемую операционку, которая _никогда_ не будет перенесена.

Re: C++:expected unqualified-id

>которая _никогда_ не будет перенесена.

так все говорят, а потом приходит тот кто платит деньги, и говорю а я хочу вот это..

Re: C++:expected unqualified-id

Она делается как очень специализированная оська для очень специфических целей. Простите за возможный понт (просто мне очень повезло), но платит большая-пребольшая фирма, которая заранее знает, чего хочет.

Re: C++:expected unqualified-id

> Пишется оно под 64 бита. Под встраиваемую операционку, которая _никогда_
> не будет перенесена.

Перенос ОС != перенос файловой системы. Вы точно уверены, что никто не захочет
подмонтировать и/или создать образ ФС на PC’юке (или ещё какой-нибудь
архитектуре)?

Re: C++:expected unqualified-id

Хоть и не мне было адресовано, но я всё же отвечу.

> Простите за возможный понт (просто мне очень повезло), но платит
> большая-пребольшая фирма, которая заранее знает, чего хочет.

Ничего страшного. Зато мы получили ещё одну возможность полюбоваться
на качество проприетарного кода.

Re: C++:expected unqualified-id

Работает принцип: «Мы можем сделать быстро, качественно, дёшево. Выберете два из этих трёх.» Чаще всего выбирают быстро и потом так никак и не могут определиться качественно или дёшево.

Re: C++:expected unqualified-id

Я все понимаю. Я _не_ программист на плюсах, и вопрос был детским. К тому же, я еще не спец, но весь код проверяется и «руководится». И мне почему-то кажется, что Вы тоже родились без талмудов Кнута в руках. Все учатся, я тоже, и вы тоже наверняка задавали глупые вопросы, не на форумах, так старшим по мозгам. Вполне естественно, что крупные фирмы берут к себе студентов интернами, а через несколько лет — на полноценную инженерную работу.
Честное слово, я ни на кого не наезжаю — я вам всем очень благодарен за ответы и ваш опыт. Особенно товарищу dilmah, который уже много раз меня спасал в сложных ситуациях.

Re: C++:expected unqualified-id

> Она делается как очень специализированная оська для очень специфических целей.

А что за железяка-то, которой она рулить будет? Интересуюсь для того, чтоб не купить её ненароком.

[offtopic] Про жизнь.

> И мне почему-то кажется, что Вы тоже родились без талмудов Кнута в руках.

Я не лез программировать ФС, да ещё и для встраиваемой ОСи. Да ещё и для production.

> Все учатся, я тоже, и вы тоже наверняка задавали глупые вопросы, не на форумах, так старшим по мозгам.

И не удивлялся, если получал в ответ втык (в том числе — и в буквальном смысле слова).

> Вполне естественно, что крупные фирмы берут к себе студентов интернами, а через несколько лет — на полноценную инженерную работу.

Ни разу это не естественно. Одновременно работать и учиться НЕ ВЫЙДЕТ. В результате и имеем таких «спецов». Как подумаю, что такие же рулят ядерными электростанциями, или лечат людей, жить страшно становится.

> Честное слово, я ни на кого не наезжаю

Я тоже. Только после общения с очередной кривой железкой очень хочется найти того, кто писал прошивку, или разводил печатную плату, etc, и как следует поблагодарить.

И вот я захожу на LOR, и вижу процесс появления такого изделия в реальном масштабе времени, так сказать.

Re: [offtopic] Про жизнь.

>Я не лез программировать ФС, да ещё и для встраиваемой ОСи.
Ну да, все начинали со змейки. Главное — ей не закончить. А для этого надо заниматься чем-то посложнее.

>Да ещё и для production.
Это еще не продакшн. Это прототип. Пруф оф концепт (с). А если оно выйдет в продакшн, но довольно нескоро.

>Одновременно работать и учиться НЕ ВЫЙДЕТ.
Сами же понимаете, что практический опыт в таких узких областях ценнее теории. Хотя здесь есть и теоретическое обучение.

>и как следует поблагодарить
Если через 4 года оно выйдет и вам не понравится — с меня ящик пива. Честно.

Re: [offtopic] Про жизнь.

> Ну да, все начинали со змейки.

Не, я начинал с падающего шарика (требовалось рассчитать траекторию падения с учётом сопротивления воздуха).

> Главное — ей не закончить.

Да некоторым (это не про Вас) лучше было бы на ней и закончить.

> Если через 4 года оно выйдет и вам не понравится — с меня ящик пива. Честно.

Слабое утешение, тем более, что я не употребяю.

Re: [offtopic] Про жизнь.

Все будет хорошо. Если весьма своеобразное высшее руководство не забросит офигенную идею. А такое уже не раз бывало 🙁

Источник

Как исправить ошибку 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 .

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

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

Источник

C++- Help (error: expected unqualified-id before ‘return’)

I have throughly looked through all streams containing this question and have found no answer that helps me solve this problem:

When trying to run this program, the debugger says that there is an unqualified-id before return- I have tried removing/adding semi-colons and brackets, and even tried to change the way the lines are spaced..

Can someone help?

Thank you very much.

2 Answers 2

Your return statement must be within a function definition. You cannot have a return statement in the global scope

Just look at your code again. I’ve edited and indented it properly.

Now you can clearly see that return 0; is outside of the int main() <> , which is incorrect. It must be before that last > .

makes no sense. It’s legal, but <> are redundant here. You can replace it with

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Error: expected unqualified-id before ‘<‘ token < [closed]

This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

Closed 4 years ago .

So I’ve been working on command line arguments in my Computer Science class and I’ve been getting this:

I’ve been trying to figure out what’s wrong with it and I can’t wrap my head around there being an an error after my first int statement?? Here’s the code. Any guidance would be much appreciated! I’m pretty much a noob when it comes to coding.

2 Answers 2

A more definitive answer to this problem would be that adding a semicolon (» ; «), which is treated as end-of-statement (except for the usage of , which is for splitting lines) in C++ and many other languages. and function names ended with these «semi-colons» are treated as a function declaration. So don’t confuse it with function definition which is what you want to do here.

Function declarations are the pre-defined function skeletons that do not have a body and have to be defined somewhere in the code. Or else the compiler will complain about the function not having a body.

Here, the compiler says something like:

«Hey this function has a semicolon at its end, I know, it is a function declaration. «

And when it reaches the next line, it is like:

«Huh!, where’s the name of this function, I know I got a semicolon at the previous line, so it couldn’t be that!«

And the compiler finally gives an error about the body not having a declaration. So, you have two options to do.

Either do something like this (Highly recommended by everyone).

Or: (Not recommended, but will not cause any problems)

Note: I’m sure the compiler would have pointed out to you which line is causing the error so you should try out some methods yourself because learning yourself gains you more experience than yearning for an answer.

Источник

  • Forum
  • General C++ Programming
  • expected unqualified-id before «»

expected unqualified-id before «»

Im getting the error expected unqualified-id before «delete» for a program that im working on and i have no ieda what to do for it.any help would be appreciated

header:

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
template<class itemtype>
class llist
{
      friend std::ostream& operator<<(std::ostream & , llist<itemtype> &);
      private:     
      struct nodetype
      {
      itemtype item;
      nodetype *next;
      };
      nodetype *first, *last;
      public:
             llist();
             void firstinsert(itemtype);
             void frontinsert(itemtype);
             void endinsert(itemtype);
             void inorderinsert(itemtype);
             bool search(itemtype);
             bool delete (itemtype); -problem line 
             bool listempty();
             itemtype firstitem();
             itemtype lastitem();
             ~llist();
};
#endif 

i just cut down my implementation code to include the problem function

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
template <class itemtype>
bool llist<itemtype>::delete (itemtype x)-problem line
{
     nodetype *cur, *prev;
     prev=null;
     cur=first;
      while ((cur!=0)&&(x!=cur->item))
     { 
            prev=cur;
            cur=cur->next;
            if(cur==0)
                return 0;
            else
            {
                delnode=cur;
                if(prev==0)
                {   
                    first=first->next;
                }
                else
                {
                prev->next=cur->next;
                if (cur==last)
                   last=prev;
                }
                delete delnode;
                return 1;
            }
     }
}

I also have the error 104 expected `;’ before «delete» for the same line too.
thanks for the help.

delete is a C++ keyword. It will cause problems if you try to use it as an identifier name.

( You will notice that the syntax highlighting shows it in the keyword colo(u)r)

alright,so how can i fix the code to get rid of those errors?

I changed the line to
delete () and im still getting the same errors.

Sorry to be a pain about this but i could use the help.

delete is an overloadable operator but it has to have void return type and get a void* parameter

so i have to change bool to void for both? can i still use the code that i already had for the function?

Yes, also remove the return lines

i did both and im still getting the errors.

header:
void delete (itemtype);

implementation:

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
template <class itemtype>
void llist<itemtype>::delete (itemtype x)
{
     nodetype *cur, *prev;
     prev=0;
     cur=first;
      while ((cur!=0)&&(x!=cur->item))
     { 
            prev=cur;
            cur=cur->next;
            if(cur==0)
           (delnode !=cur)
            else
            {
                delnode=cur;
                if(prev==0)
                {   
                    first=first->next;
                }
                else
                {
                prev->next=cur->next;
                if (cur==last)
                   last=prev;
                }
                delete delnode;
            }
     }
}

delete is a keyword in C++. Rename your delete function to something else.

thanks i fixed it

Topic archived. No new replies allowed.

Я пишу C++ связанный список. Я внедрил и протестировал вставку и печать. Однако я не могу вернуть указатель узла для удаления. Я получаю эти ошибки при попытке удалить:

    Node.h:11: error: expected unqualified-id before "delete"
    Node.h:11: error: abstract declarator 'Node*' used as declaration
    Node.h:11: error: expected ';' before "delete"

    Node.cpp:21: error: expected unqualified-id before "delete"
    Node.cpp:21: error: expected init-declarator before "delete"
    Node.cpp:21: error: expected ',' or ';' before "delete"

    make.exe: *** [Node.o] Error 1

    Execution terminated

Вот мой код:

node.h

    #ifndef Node_H
    #define Node_H


    class Node{
          int data;
          Node* next;

    public:
           Node(int data);       
           void insert(int d);
           Node* delete(int d);
           void printOut(void);
    };

    #endif

node.cpp

    #include <stdio.h>
    #include "Node.h"

    Node::Node(int d){
          data = d;
          next = NULL;
          }

    void Node::insert(int d){

          Node* n = this;
          Node* current = new Node(d);

          while(n->next != NULL){
                  n = n->next;                   
                  }

          n->next = current;
          }

    Node* Node::delete(int d){

          Node* head = this;
          Node* n = this;

          if (n->data = null){
             return n;
             }

          if (n->data == d){
             return n->next;
             }

          while(n->next != NULL){

          if (n->next->data == d){
             n->next = n->next->next;
             return head;
             }

          n = n->next;

          }

        return head;

        }

    void Node::printOut(void){

         Node* n = this;

         while(n->next != NULL){
                      printf("%d ->", n->data);
                       n = n->next;                   
                       }

         printf("%d n", n->data);

         }

главный:

    #include <iostream>
    #include <stdio.h>
    #include <cstdlib>

    #include "Node.h"
    using namespace std;

    int main (void){
        int i = 0;

        Node* root = new Node(111);
        Node* result;

        for (i = 0; i < 9; i++){
            root->insert(i);
            } 

        root->printOut();

        result = root->delete(5);

        result->printOut();

        printf("Hello j n");

        getchar();
        delete[] root; 
        return 0;   
    }

Хм, тогда вот так

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <windows.h>
 
 
WNDCLASSEX tr;        // Класс окна графиков
PAINTSTRUCT trps;     //структура рисования графиков
HWND hTrWnd;          // Дескриптор окна графиков
HRGN hrgn;
char trClassName[] = "TrClass"; //имя класса окна графиков
 
int TrendWnd_lx, TrendWnd_ly, TrendWnd_rx, TrendWnd_ry;
int sx, sy;
 
HPEN TrendLinePen[8];
for(int i=0; i<8; i++)
{
  TrendLinePen[i]=CreatePen(PS_SOLID, 1, RGB(250/i, i*15, i*30))
}
 
HPEN ZeroLinePen[8]
for(int i=0; i<8; i++)
{
  ZeroLinePen[i]=CreatePen(PS_SOLID, 1, RGB(i, i*2, i*4))
}
 
static HPEN DefaultPen = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
static HPEN RectanglePen = CreatePen(PS_SOLID, 4, RGB(0, 0, 0));
static HPEN HorisontalLinePen = CreatePen(PS_DOT, 1, RGB(0, 0, 0));
static HPEN VerticalLinePen = CreatePen(PS_DOT, 1, RGB(0, 0, 0));
 
class GRAPH
{
  public:
     GRAPH();
     GRAPH(int ZeroPoint, HPEN Z_Pen, HPEN L_Pen);
     ~GRAPH();
     void SetZeroPoint(int ZeroPoint){zPoint = TrendWnd_ry + ZeroPoint;} //установка 0 графика по Y
     int  GetZeroPoint(void){return zPoint;}                             //получить нулевую точку
     void SetZeroLinePen(HPEN Pen){ZeroLinePen = Pen;}                   //
     void SetLinePen(HPEN Pen){LinePen = Pen;}                           //
     void SetLinePoint(int xL_Point, int yL_Point){xPoint = xL_Point; yPoint = yL_Point;}//
     void StartPoint(void){MoveToEx(hdc, TrendWnd_lx, zPoint, NULL);}    //
     void DrawLine(int xLinePoint, int yLinePoint);                      //
     void PutZeroLine(void);                                             //
  private:
     HPEN ZeroLinePen;
     HPEN LinePen;
     int zPoint;
     int xPoint;
     int yPoint;
};
 
GRAPH::GRAPH()
{
   ZeroLinePen = DefaultPen;
   LinePen = DefaultPen;
   zPoint = 0;
   xPoint = 0;
   yPoint = 0;
}
 
GRAPH::GRAPH(int ZeroPoint, HPEN Z_Pen, HPEN L_Pen)
{
  SetZeroPoint(ZeroPoint);
  ZeroLinePen = Z_Pen;
  yPoint = zPoint;
  LinePen = L_Pen;
}
 
GRAPH::~GRAPH()
{
  delete  ZeroLinePen;
  delete  LinePen;
}
 
void GRAPH::PutZeroLine(void)//рисуем нулевую линию
{
  SelectObject(hdc, ZeroLinePen);
  MoveToEx(hdc, TrendWnd_lx, zPoint, NULL);
  LineTo(hdc, TrendWnd_rx, zPoint);
  SelectObject(hdc, LinePen);
  MoveToEx(hdc, TrendWnd_lx, zPoint, NULL);
}
 
void GRAPH::DrawLine(int xLinePoint, int yLinePoint)
{
   int x, y;
   SelectObject(hdc, LinePen);
   StartPoint();
   for(x=TrendWnd_lx, y=zPoint; x<TrendWnd_rx; x+=10, y+=2)
   {
      LineTo(hdc, x, y);
   }
}

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

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
GRAPH* graph[8];
for(int i=0; i<8; i++)
{
  graph[i] = new GRAPH(i*50, DefaultPen, DefaultPen);
}
 
struct trend    //структура для хранения показаний 8 АЦП
{
   char graph1;
   char graph2;
   char graph3;
   char graph4;
   char graph5;
   char graph6;
   char graph7;
   char graph8;
};
 
struct voltage  //структура для хранения установок 3 ШИМ
{
   char vol1;
   char vol2;
   char vol3;
};
//-----------------------------------------------------------------------------------------
 
int InitWindow(int sx, int sy);
ATOM MyRegisterChildClass();
void Marker(LONG x, LONG y, HWND hTrWnd);
LRESULT CALLBACK TrGraphProc(HWND, UINT, WPARAM, LPARAM);
 
 
 
ATOM MyRegisterChildClass()
    {// Заполняем структуру класса окна
       tr.cbSize = sizeof(tr);
       tr.style = CS_HREDRAW | CS_VREDRAW;// Стили класса, в данном случае - окна этого класса будут перерисовываться при изменении размеров по вертикали и горизонтали
       tr.lpfnWndProc = TrGraphProc;// Указатель на функцию, обрабатывающую оконные сообщения
       tr.cbClsExtra = 0;        // Нет дополнительных данных класса 
       tr.cbWndExtra = 0;        // Нет дополнительных данных окна
       tr.hInstance = hInstance; // дескриптор приложения, который регистрирует класс
       tr.hIcon = LoadIcon(NULL, IDI_APPLICATION); // Стандартная иконка
       tr.hCursor = LoadCursor(NULL, IDC_CROSS);   //курсор - перекрестие
       tr.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);// Цвет фона рабочей области окна
       tr.lpszMenuName = NULL;   // Нет меню
       tr.lpszClassName = "TrClass"; // Имя класса окна
       tr.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
       return RegisterClassEx(&tr);
    }
 
//--------------------------------------------------------------------------------------------------------------------------------------------  
    
int InitWindow(int sx, int sy)
{  
   int x, y;
   TrendWnd_lx = 0;
   TrendWnd_ly = 0;
   TrendWnd_rx = sx;
   TrendWnd_ry = -sy;
 
   hbrush = CreateSolidBrush(RGB(255, 255, 255));
   
   SetMapMode(hdc, MM_ISOTROPIC);//текущий режим отображения 
   SetViewportExtEx(hdc, sx, sy, NULL);     //физический размер области экрана в пикселах
   SetWindowExtEx(hdc,  sx, sy, NULL);      //логические размеры окна в пикселах
   
   SelectObject(hdc, hbrush);
   SelectObject(hdc, RectanglePen);
   Rectangle(hdc, TrendWnd_lx, TrendWnd_ly, TrendWnd_rx, TrendWnd_ry);
   for (x = TrendWnd_lx; x < TrendWnd_rx; x += (TrendWnd_rx/10))//чертим вертикальные линии
   {
      SelectObject(hdc, VerticalLinePen);
      MoveToEx(hdc, x, TrendWnd_ly, NULL);
      LineTo(hdc, x, -TrendWnd_ry);
   }
   for (y = TrendWnd_ly; y < -TrendWnd_ry; y += ((-TrendWnd_ry)/10))//чертим горизонтальные линии
   {
      SelectObject(hdc, HorisontalLinePen);
      MoveToEx(hdc, TrendWnd_lx, y, NULL);
      LineTo(hdc, TrendWnd_rx, y);
   }
   SelectObject(hdc, hbrush);
   
   SetWindowExtEx(hdc,  sx, -sy, NULL);      //логические размеры окна в пикселах, ось Y вверх
   ///////////////////////////
   for(int i = 0; i<8; i++)
   {
     graph[i]->DrawLine(400, 444);
   }
   ///////////////////////////
 
}



0



Expected unqualified id errorThe expected unqualified id error shows up due to mistakes in the syntax. As there can be various situations for syntax errors, you’ll need to carefully check your code to correct them. Also, this post points toward some common mistakes that lead to the same error.

Go through this article to get an idea regarding the possible causes and gain access to the solutions to fix the given error.

Contents

  • Why Are You Getting the Expected Unqualified Id Error?
    • – Missing or Misplaced Semicolons
    • – Extra or Missing Curly Braces
    • – String Values Without Quotes
  • How To Fix the Error?
    • – Get Right With Semicolons
    • – Adjust the Curly Braces To Fix the Expected Unqualified Id Error
    • – Wrap the String Values inside Quotes
  • FAQ
    • – What Does a Qualified ID Mean?
    • – What Does the Error: Expected ‘)’ Before ‘;’ Token Inform?
    • – What Do You Mean By Token in C++?
  • Conclusion

Why Are You Getting the Expected Unqualified Id Error?

You are getting the expected unqualified-id error due to the erroneous syntax. Please have a look at the most common causes of the above error.

– Missing or Misplaced Semicolons

You might have placed a semicolon in your code where it wasn’t needed. Also, if your code misses a semicolon, then you’ll get the same error. For example, a semicolon in front of a class name or a return statement without a semicolon will throw the error.

This is the problematic code:

#include <iostream>
using namespace std;
class myClass;
{
private:
string Age;
public:
void setAge(int age1)
{
Age = age1;
}
string getAge()
{
return Age
}
}

Now, if your code contains extra curly braces or you’ve missed a curly bracket, then the stated error will show up.

The following code snippet contains an extra curly bracket:

#include <iostream>
using namespace std;
class myClass;
{
private:
string Age;
public:
void setAge(int age1)
{
Age = age1;
}
}
}

– String Values Without Quotes

Specifying the string values without quotes will throw the stated error.

Here is the code that supports the given statement:

void displayAge()
{
cout << Your age is << getWord() << endl;
}

How To Fix the Error?

You can fix the mentioned unqualified-id error by removing the errors in the syntax. Here are the quick solutions that’ll save your day.

– Get Right With Semicolons

Look for the usage of the semicolons in your code and see if there are any missing semicolons. Next, place the semicolons at their correct positions and remove the extra ones.

Here is the corrected version of the above code with perfectly-placed semicolons:

#include <iostream>
using namespace std;
class myClass
{
private:
string Age;
public:
void setAge(int age1)
{
Age = age1;
}
string getAge()
{
return Age;
}
}

– Adjust the Curly Braces To Fix the Expected Unqualified Id Error

You should match the opening and closing curly braces in your code to ensure the right quantity of brackets. The code should not have an extra or a missing curly bracket.

– Wrap the String Values inside Quotes

You should always place the string values inside quotes to avoid such errors.

This is the code that will work fine:

void displayAge()
{
court << “Your age is” << getWord() << endl;
}

FAQ

You can have a look at the following questions and answers to enhance your knowledge.

– What Does a Qualified ID Mean?

A qualified-id means a qualified identifier that further refers to a program element that is represented by a fully qualified name. The said program element can be a variable, interface, namespace, etc. Note that a fully qualified name is made up of an entire hierarchical path having the global namespace at the beginning.

– What Does the Error: Expected ‘)’ Before ‘;’ Token Inform?

The error: expected ‘)’ before ‘;’ token tells that there is a syntax error in your code. Here, it further elaborates that there is an unnecessary semi-colon before the closing round bracket “).” So, you might get the above error when you terminate the statements that don’t need to be ended by a semi-colon.

– What Do You Mean By Token in C++?

A token is the smallest but important component of a C++ program. The tokens include keywords, punctuators, identifiers, etc. For example, you missed a semi-colon in your code because you considered it something that isn’t very important. But the C++ compiler will instantly show up an error pointing towards the missing “;” token.

Conclusion

The unqualified id error asks for a careful inspection of the code to find out the mistakes. Here are a few tips that’ll help you in resolving the given error:

  • Ensure the correct placement of semicolons
  • Aim to have an even number of curly brackets
  • Don’t forget to place the text inside the quotes

How to fix expected unqualified idNever write the code in hurry, you’ll only end up making more mistakes, and getting such errors.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

#include <SoftwareSerial.h>

SoftwareSerial wifiSerial(2, 3);

#define RED 11
#define GRN 12
#define BLU 13

void setup()
{
  pinMode(RED, OUTPUT);
  pinMode(GRN, OUTPUT);
  pinMode(BLU, OUTPUT);

  Serial.begin(115200);
  while (!Serial) {
    ;
  }
}

void loop() {
  digitalWrite(RED, LOW);
  digitalWrite(GRN, LOW);
  digitalWrite(BLU, LOW);
}
if (Serial.available() > 0) {
  String message = readSerialMessage();
}

if (find(message, "debugEsp8266:")) {   //Вот здесь выдает ошибку
  String result = sendToWifi(message.substring(13, message.length()), responseTime, DEBUG);
  if (find(result, "OK")) {
    sendData("nOK");
    else
      sendData("nEr");
  }
  if (wifiSerial.available() > 0) {

    String message = readWifiSerialMessage();

    if (find(message, "esp8266:")) {
      String result = sendToWifi(message.substring(8, message.length()), responseTime, DEBUG);
      if (find(result, "OK"))
        sendData("n" + result);
      else
        sendData("nErrRead");               //At command ERROR CODE for Failed Executing statement
    } else if (find(message, "Red")) { //receives HELLO from wifi
      sendData("\nOh, red!")
      digitalWrite(RED, HIGH)
      delay(5000);    //arduino says HI
    } else if (find(message, "Green")) {
      //turn on built in LED:
      sendData("\nOh, green!")
      digitalWrite(GREEN, HIGH)
      delay(5000);
    } else if (find(message, "Blue")) {
      //turn off built in LED:
      sendData("\nOn, blue!")
      digitalWrite(BLUE, HIGH)
      delay(5000);
    }
    else {
      sendData("nErrRead");                 //Command ERROR CODE for UNABLE TO READ
    }
    delay(responseTime);
  }
}

Понравилась статья? Поделить с друзьями:
  • Error expected to return a value at the end of arrow function consistent return
  • Error expected string or bytes like object
  • Error expected specifier qualifier list before static
  • Error expected property shorthand object shorthand
  • Error expected primary expression before unsigned