Error expected unqualified id before token ошибка

Basic Infos This issue complies with the issue POLICY doc. I have read the documentation at readthedocs and the issue is not addressed there. I have tested that the issue is present in current mast...

On building a sample piece of code for an ESP8266 Module I am unable to compile. The error I am seeing when running Verify in the Arduino IDE is:

Arduino: 1.8.8 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Build options changed, rebuilding all
In file included from C:UsersyomaguirAppDataLocalArduino15packagesesp8266hardwareesp82662.5.0librariesESP8266WiFisrc/WiFiClient.h:25:0,

                 from C:UsersyomaguirAppDataLocalArduino15packagesesp8266hardwareesp82662.5.0librariesESP8266WiFisrc/ESP8266WiFi.h:39,

                 from C:UsersyomaguirDocumentsArduinolibrariesAzureIoTUtilitysrcadapterssslClient_arduino.cpp:9:

c:usersyomaguirappdatalocalarduino15packagesesp8266toolsxtensa-lx106-elf-gcc2.5.0-3-20ed2b9xtensa-lx106-elfincludec++4.8.2bitsrandom.tcc: In member function 'void std::poisson_distribution<_IntType>::param_type::_M_initialize()':

C:UsersyomaguirAppDataLocalArduino15packagesesp8266hardwareesp82662.5.0coresesp8266/Arduino.h:137:22: error: expected unqualified-id before '(' token

 #define round(x)     ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))

                      ^

c:usersyomaguirappdatalocalarduino15packagesesp8266toolsxtensa-lx106-elf-gcc2.5.0-3-20ed2b9xtensa-lx106-elfincludec++4.8.2bitsrandom.tcc: In member function 'void std::binomial_distribution<_IntType>::param_type::_M_initialize()':

C:UsersyomaguirAppDataLocalArduino15packagesesp8266hardwareesp82662.5.0coresesp8266/Arduino.h:137:22: error: expected unqualified-id before '(' token

 #define round(x)     ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))

                      ^

C:UsersyomaguirAppDataLocalArduino15packagesesp8266hardwareesp82662.5.0coresesp8266/Arduino.h:137:22: error: expected unqualified-id before '(' token

 #define round(x)     ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))

                      ^

exit status 1
Error compiling for board Generic ESP8266 Module.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

BananEvgeniy

0 / 0 / 0

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

Сообщений: 7

1

16.12.2017, 00:40. Показов 38215. Ответов 14

Метки dev-c++ (Все метки)


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
#include <iostream>
#include <math.h>
using namespace std;
int count;
 
 
 
    int main(0);
    {
    
for (i=0,i<11,i++)
 
    {
    X[i]=rand()%25-10;
    Y[i]=rand()%25-10;
}
for (i=0,i<11,i++)
 
    if(X[i]=Y[i])
    {
    
        count++;
        cout<<X[i];
}
    return 0;
}

Ругается на самую первую {

что не так?

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



0



437 / 429 / 159

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

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

16.12.2017, 01:21

2

int main()

Добавлено через 38 секунд
в for заменить запятые на точку с запятой

Добавлено через 53 секунды
объявить массивы X и Y до их использования

Добавлено через 42 секунды
инициализировать count перед первым использованием

Добавлено через 3 минуты
и еще несколько ошибок



0



3985 / 3255 / 909

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

Сообщений: 12,102

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

16.12.2017, 01:37

3

int main(0);
убрать точку с 3апятой



0



0 / 0 / 0

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

Сообщений: 7

16.12.2017, 22:46

 [ТС]

4

все равно не помогает, может код неправильынй какой-то?я не сильно еще разбираюсь тут



0



wareZ1400

12 / 13 / 2

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

Сообщений: 208

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

16.12.2017, 22:58

5

BananEvgeniy,

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <math.h>
using namespace std;
int c = 0;
int X[10];
int Y[10];
 
int main()
{
    for (int i = 0; i < 11; i++)
    {
        X[i] = rand() % 25 - 10;
        Y[i] = rand() % 25 - 10;
    }
    for (int i = 0; i < 11; i++)
        if (X[i] == Y[i])
        {
            c++;
            cout << X[i];
        }
    return 0;
}



0



Kuzia domovenok

3985 / 3255 / 909

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

Сообщений: 12,102

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

17.12.2017, 00:17

6

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

C++
1
2
int X[10];
 int Y[10];

учи матчасть!

C++
1
2
int X[11];
 int Y[11];

Добавлено через 1 минуту

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

int main()
Добавлено через 38 секунд
в for заменить запятые на точку с запятой
Добавлено через 53 секунды
объявить массивы X и Y до их использования
Добавлено через 42 секунды
инициализировать count перед первым использованием
Добавлено через 3 минуты
и еще несколько ошибок

wareZ1400, ты точно прочитал этот коммент и переписал с учётом всех замечаний?



0



wareZ1400

12 / 13 / 2

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

Сообщений: 208

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

17.12.2017, 02:52

7

Kuzia domovenok, точно прочитать коммент и переписал с учетом всех замечаний.

Вот:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <math.h>
using namespace std;
int c = 0;
int X[11];
int Y[11];
 
int main()
{
    for (int i = 0; i < 11; i++)
    {
        X[i] = rand() % 25 - 10;
        Y[i] = rand() % 25 - 10;
    }
    for (int i = 0; i < 11; i++)
        if (X[i] == Y[i])
        {
            c++;
            cout << X[i];
        }
    return 0;
}



0



0 / 0 / 0

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

Сообщений: 7

17.12.2017, 21:53

 [ТС]

8

все равно не работает
выделяет X[i] = rand() % 25 — 10; вот эту стрчоку красным и пишет [Error] ‘rand’ was not declared in this scope



0



0 / 0 / 2

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

Сообщений: 16

17.12.2017, 22:06

10

Ну правильно. Убери нахрен ; там где int main();



0



0 / 0 / 0

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

Сообщений: 7

17.12.2017, 22:46

 [ТС]

11

уже давно убрал, все равно ошибку пишет



0



Comevaha

0 / 0 / 2

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

Сообщений: 16

22.12.2017, 20:24

12

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
#include <iostream>
#include <math.h>
using namespace std;
int count;
 
int X[11];
int Y[11];
 
int main(){
    for (auto i=0;i<11;i++)
    {
        X[i]=rand()%25-10;
        Y[i]=rand()%25-10;
    }
 
    for (auto i=0;i<11;i++)
    {
 
        if(X[i]==Y[i])
        {
            count++;
            cout<<X[i];
        }
    }
    return 0;
}

Берите код. Работает



0



12 / 13 / 2

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

Сообщений: 208

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

24.12.2017, 01:37

13

Comevaha, а Вы каким компилятором компилите?



0



0 / 0 / 2

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

Сообщений: 16

24.12.2017, 14:20

14

Mingw



0



12 / 13 / 2

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

Сообщений: 208

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

24.12.2017, 15:57

15

Comevaha, то, что я написал компилится в ms visual studio. А почему у других может не компилиться?



0



#include<iostream>
#include<conio.h>
using namespace std;

maxResult(float eq1,float eq2,float eq3){

if(eq1>eq2 && eq1>eq3){
cout<< «Equation 1:»<<» «<<eq1<<» «<<«=»» result=»» is=»» maximumn»<<endl;
=»»
=»» }
=»» else=»» if(eq2=»»>eq1 && eq2>eq3){
cout<<«Equation 2:»<<» «<<eq2<<» «<<«result=»» is=»» maximumn»<<endl;
=»»
=»» }
=»» else=»» if(eq3=»»>eq1 && eq3>eq2){

cout<<«Equation 3:»<<» «<<eq3<<» «<<«result=»» is=»» maximumn»<<endl;
=»» }
}
=»»
=»» else

calculateequationresult()
{
=»» float=»» eq1;
=»» eq2;
=»» eq3;
=»» a;
=»» b;
=»» c;
=»» d;
=»» x;
=»» int=»» count=»0
» while(count<2){
=»» a=»6;
» b=»7;
» c=»8;
» d=»9;
» x=»11;
» }
=»» else{
=»» eq1=»x+(b/(3*a))
» eq2=»(3*a*c-b*b)/(3*a*a);
» eq3=»(2*b*b*b-9*(a+b+c)+(27+a*a*a);
cout<<«Equation» 1:»<<«»<<eq1<<endl;
cout<<«equation=»» 2:»<<«»<<eq2<<endl;
cout<<«equation=»» 3:»<<«»<<eq3<<endl;

maxresult(eq1,eq2,eq3)
}

int=»» main()
{=»» char=»» choice;

bool=»» run=»true;

while(run)
{
» do{
=»» calculateequationresult();
=»» cout<<«would=»» you=»» like=»» to=»» perform=»» other=»» calculation?(y=»» n)»;
=»» cin=»»>>choice;
choice=tolower(choice);
}
while(choice!=’n’ && choice!=’y’);

if(choice==’n’){
run=false;

}
}
result 0;
}

}

Содержание

  1. ERROR: expected unqualified-id before ‘(‘ token #5787
  2. Comments
  3. Basic Infos
  4. Platform
  5. Settings in IDE
  6. Problem Description
  7. Debug Messages
  8. Temporary fix
  9. Footer
  10. Arduino.ru
  11. Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru
  12. forum.arduino.ru
  13. Ошибки в скетчи.

ERROR: expected unqualified-id before ‘(‘ token #5787

Basic Infos

  • This issue complies with the issue POLICY doc.
  • I have read the documentation at readthedocs and the issue is not addressed there.
  • I have tested that the issue is present in current master branch (aka latest git).
  • I have searched the issue tracker for a similar issue.
  • If there is a stack dump, I have decoded it.
  • I have filled out all fields below.

Platform

  • Hardware: Sparkfun ESP8266 Thing Dev
  • Core Version: 2.5.0
  • Development Env: Arduino IDE
  • Operating System: Windows

Settings in IDE

  • Module: Generic ESP8266 Module
  • Flash Mode: N/A
  • Flash Size: N/A
  • lwip Variant: N/A
  • Reset Method: N/A
  • Flash Frequency: N/A
  • CPU Frequency: N/A
  • Upload Using: N/A
  • Upload Speed: N/A

Problem Description

On building a sample piece of code for an ESP8266 Module I am unable to compile. The error I am seeing when running Verify in the Arduino IDE is:

Debug Messages

The text was updated successfully, but these errors were encountered:

The issue template requires a MCVE sketch to reproduce. Without that, it’s unlikely this will be looked at.
Please provide a minimal sketch to reproduce the issue.

I encountered the same error after updating to 2.5.0

Arduino IDE Version: 1.8.8
Board Manager: Adafruit Feather HUZZAH ESP8266 Version 2.5.0
Library: AzureIoTHub Version 1.0.45

It is a compilation issue.

PlatformIO 3.6.4 | VSCode 1.31.1
Board: Wemos D1 Mini
Library: esp8266/Arduino 2.5.0

Ok, so I found the underlying error in random.tcc (the file from our compilation errors).

This is the function that is responsible for the compilation error:

«round» in std::round() gets replaced by the round macro in Arduino.h , thus rendering the syntax faulty and not compilable.

Temporary fix

Commenting out line 137 in Arduino.h fixes the problem and the code compiles as usual.

Yep. Seems like ESP8266 is trying to redefine round, but it’s literally the same? Can the ESP8266 folks explain this block of code in the ESP8266 Arduino.h?

Vanilla Arduino.h:

ESP8266 Arduino.h:

ESP Arduino.h was just a forked copy of arduino.cc’s Arduino.h as far as I understand it.

I personally think these macros are an awful construct, but it’s a compatibility thing having those macros (esp. since . round returns a float/double on most every system out there while this macro returns a long.

That said, it looks like both AVR arduino and esp8266 arduino match here. Do you have some other Arduino chip where this #define round(x) is not present in the header (i.e. one where you could build your sample successfully)?

Then we could say we’re still Arduino compatible and remove these ugly bits.

Yep. Seems like ESP8266 is trying to redefine round, but it’s literally the same?

This question would be asked to «vanilla» arduino folks.
We would like (at least I) to remove it but we can’t (can we?), side effects are supposed to be unpredictable when it comes to compatibility with arduino.

There are three versions of round, the one in math.h, the one in libstdc++ ( std::round() ) and this define which breaks standard c++ code using std::round , this issue. If possible, one can put #undef round where std::round is needed (or libc’s). That way core sources don’t need to be modified.

The least we could do is

which is saner (same goes with the other macros) (because of only one evaluation of (x) ).

The other way to avoid the issue in your code is to just add #undef round immediately before the offending include/source files.

I am curious why this macro error just started ocurring in v2.5.0. Did something in the Arduino.h library change from the previous version?

That said, it looks like both AVR arduino and esp8266 arduino match here. Do you have some other Arduino chip where this #define round(x) is not present in the header (i.e. one where you could build your sample successfully)?

it looks like in ESP32 they’re overriding «vanilla» Arduino.h macros with those from std.

Also as someone with no knowledge really of the arduino board manager design, is there a reason for the fork of Arduino.h for ESP8266 except for when you want to redefine certain definitions?

I also have @KarateBrot’s question. It looks like espressif had a PR for ESP32 recently to redefine their round and abs values, so perhaps there was a breaking change somewhere else that affected everyone.

The other way to avoid the issue in your code is to just add #undef round immediately before the offending include/source files.

I added #undef round in my ino file at start but still receiving this error. Commenting corresponding line in Arduino.h fixes problem.

To get past this i deleted the #define line in the ESP8266 library manually.

To get past this i deleted the #define line in the ESP8266 library manually.

I did delete #define round(x). My arduino works fine. but it does not connect iothub.

After reading through, it seems like this can be closed. The workaround breaks Arduino compatibility (which, in this case, I think is perfectly fine because the Arduino macro is a brain dead leftover from a time when they didn’t have any FP in the AVR), so it can’t be part of our core.

Actually, the code snippet shown requires the real double round(double) method to function properly. So, your change (or just adding #undef round after including Arduino.h is needed to make the Azure code work.

De-crufting Arduino.h is a bigger discussion and probably needs to be held in arduino.cc’s repos so that every Arduino plug-in will follow through.

After reading through, it seems like this can be closed. The workaround breaks Arduino compatibility (which, in this case, I think is perfectly fine because the Arduino macro is a brain dead leftover from a time when they didn’t have any FP in the AVR), so it can’t be part of our core.

Actually, the code snippet shown requires the real double round(double) method to function properly. So, your change (or just adding #undef round after including Arduino.h is needed to make the Azure code work.

De-crufting Arduino.h is a bigger discussion and probably needs to be held in arduino.cc’s repos so that every Arduino plug-in will follow through.

What change? Trying/failing to compile adafruit ESP8266 azure sample code brought me here. What exactly is the necessary change? If commenting out the def breaks iothub, then how to not break it? Thanks.

What change? Trying/failing to compile adafruit ESP8266 azure sample code brought me here. What exactly is the necessary change? If commenting out the def breaks iothub, then how to not break it? Thanks.

A workaround for me was to comment (or delete) the round macro in arduino.h (#define round(x) . ) because it clashes with std::round of c++. Maybe you need to comment other macros but at least for me it was a problem with round.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Arduino.ru

Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru

forum.arduino.ru

Ошибки в скетчи.

Здравствуйте, у меня вот такой скетч:

При компиляции скетча вылетет такая ошибка:

Версия ардуины 1.6.0

Ну, как минимум, количество открывающих фигурных скобок (6 шт.) не соответсвует количеству закрывающих (7 шт., лишняя в строке 32). И два раза подряд else (строки 28, 34), перед каждым else должен быть свой if.

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

операторы иф, елсе сами надеюсь поправите, не хочу ковыряться с вашими проверками. используйте их правильно и будет работать. а вообще заведите себе шаманский бубен програмиста, он помогает 🙂 с его помощью входите в транс и проникайте внутрь программы. и все.

http://arduino.ru/Reference/Else приведенные пример 2 гумно — новичку быстрее запутаться, чем разобраться

операторы после иф и елсе возмите за правило писать в < >я обычно делаю отступы

Странно, скетч показан что вкружен, но ардуино и датчик не хотят работать.

У меня вот ещё один вопрос. на этом видио https://www.youtube.com/watch?v=GVXQKYpCsNw объясняется как устронить основную проблему этого датчик HC-SR04. Но я не могу понять куда он этот доп. код нужно вставить( Пожалуйста, могли бы вы мне помочь. Вот этот код, который на видео:

duration = pulseIn(echoPin, HIGH);

Serial.println(«Reload ultrasonic, fix bug SR04» );

const int Trig = 8;

операторы после иф и елсе возмите за правило писать в < >я обычно делаю отступы

Я конечно извеняюсь, но Вы используете плохой стиль оформления кода. Советовать его новичкам — категорически не стоит.

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

понятнее намного будет писать так

а если вложенный, то

так понятно, что и где закрывается, и помогает от того, что все компилится, а работает не так

Прссститте! А можно уточнить? Очень важный для меня момент — по 10 минут по утрам трачу: вот с какого конца яйцо-в-смятку нужно разбивать? Вроде с тупого положено? Я где-то читал, что учить новичков разбивать с острого конца — это путь в АДДДД! Это так?

Скажите, почему этот скетч не фурычит.

форматирование кода не по феншую

ребята помогите пожалуйста. вот код

при попытке компиляции выходят такие ошибки

kod:7: error: found ‘:’ in nested-name-specifier, expected ‘::’

kod:7: error: ‘http’ does not name a type

H:проекты_arduinoСЂРѕР±РѕС‚ тележкаинет СЂРѕР±РѕС‚2 вариантkodkod.ino: In function ‘void loop()’:

kod:31: error: ‘LedStep’ was not declared in this scope

kod:36: error: ‘LedStep’ was not declared in this scope

kod:41: error: ‘LedStep’ was not declared in this scope

exit status 1
found ‘:’ in nested-name-specifier, expected ‘::’

что это за ошибки? код рабочий так как делал по статье

Убери ссылку из 7 строки. Если копипастишь откуда-то код — будь внимательнее.

форматирование кода не по феншую

Дядя шутить изволит ,убери ссылку и объяви переменную

вот твоя 7 и 8 строка

Здравствуйте, у меня вот такой скетч:

При компиляции скетча вылетет такая ошибка:

Это всё я исправил, скетч в ардуину вгрузился, но сама она и датчик не работают.

Тоесть на выходах ничего нету.

После void loop() <

у вас не хватает этих трёх строчек:

digitalWrite(11, LOW);
delayMicroseconds(2);
digitalWrite(11, HIGH);

Люди добрые, сорри, если злой офф-топ, но. всё ж это краем-то со скетчем связано 🙂

Старые файлы проектов *.ino открываются пустыми (сейчас ide v. 1.6.5). Хотя я с тех пор их не менял. Да и если на размер их посмотреть — они разного размера. И от пустого файла проекта отличаются. Как из них код вытащить? Качать и ставить старые версии IDE? А может какой редактор хитрый есть (а то нотпад тоже пустоту показывает :(( )

Люди добрые, сорри, если злой офф-топ, но. всё ж это краем-то со скетчем связано 🙂

Старые файлы проектов *.ino открываются пустыми (сейчас ide v. 1.6.5). Хотя я с тех пор их не менял. Да и если на размер их посмотреть — они разного размера. И от пустого файла проекта отличаются. Как из них код вытащить? Качать и ставить старые версии IDE? А может какой редактор хитрый есть (а то нотпад тоже пустоту показывает :(( )

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

Та не, на права бы он ругался. И на другой машине тоже были бы «вопросы» от системы. А ИДЕ просто открывает файл. Но открывает — пустым. А размер в килобайтах есть. То есть там есть что-то. Но как его открыть. Вот я и подумал, может кто с такой же проблеммой сталкивался уже и решение нашел.

UPD: в просмотрщике Командера, в двоичном и шестнадцатиричном режимах показывает, что файлы забиты нолями :((( Печаль. Как так вышло. Нолями, и файлы разных размером. Мистика.

Та не, на права бы он ругался. И на другой машине тоже были бы «вопросы» от системы. А ИДЕ просто открывает файл. Но открывает — пустым. А размер в килобайтах есть. То есть там есть что-то. Но как его открыть. Вот я и подумал, может кто с такой же проблеммой сталкивался уже и решение нашел.

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

*скопируй на флешку и открой на другом компе.

Ну пусть я нуб, ладно.

Может у тебя не нолями забитый файл откроется 🙁

Ну пусть я нуб, ладно.

Может у тебя не нолями забитый файл откроется 🙁

да нули — не знаю, как можно такое сотворить.

Вооот. вынипарериишь! просто сохранил в своё время проекты и оставил так до лучших времен. ХЗ, что это. Тот, что прислал — в мае прошлого года делался. Чудеса в IDE. :))

при чём здесь ИДЕ?

ребята не пойму прикола. вот код

нажимаю 1 раз компилить выходят вот эти ошибки-

C:Program Files (x86)Arduino_newlibrariescyberlibCyberLib.cpp:199:37: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

C:Program Files (x86)Arduino_newlibrariescyberlibCyberLib.cpp:200:37: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

C:Program Files (x86)Arduino_newlibrariescyberlibCyberLib.cpp: In function ‘uint8_t ReadEEPROM_Byte(uint8_t)’:

C:Program Files (x86)Arduino_newlibrariescyberlibCyberLib.cpp:209:37: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

C:Program Files (x86)Arduino_newlibrariescyberlibCyberLib.cpp: In function ‘uint32_t ReadEEPROM_Long(uint8_t)’:

C:Program Files (x86)Arduino_newlibrariescyberlibCyberLib.cpp:220:55: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

uint32_t ir_code = eeprom_read_byte((uint8_t*)addr+3);

C:Program Files (x86)Arduino_newlibrariescyberlibCyberLib.cpp:221:63: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

ir_code = (ir_code Войдите на сайт для отправки комментариев

Источник

06-17-2019


#1

Ctylersills is offline


Registered User


expected unqualified ID before’.’ token

I keep running into this issue, all the information Ive searched for regarding this error have been in regards to nesting classes and other issues. Here’s some example code:

Code:

#include <iostream>

using namespace std;

class Chef
{
public:
    void makechicken()
    {
        cout<<"The chef makes chicken"<<endl;
    }
    void makeSalad()
    {
        cout<<"The chef makes salad"<<endl;
    }
    void makeSpecialDish()
    {
        cout<<"The chef makes bbq ribs"<<endl;
    }
};

int main()
{
    Chef chicken;
    Chef.makeChicken();

    return 0;
}

Can someone please explain this error and what I’m doing wrong, I went over a few tutorials I watched originally, when I started learning c++, and this usage seems to be correct. Help please.


Hi all,

I’m having a little problem with array and some «unqualified-id» problem. I’ve created gazillions (okay, maybe 80) arrays before but I had never encountered such problem. Especially with static arrays.

#include <stdio.h>
#include <cstdlib>
using namespace std;

int main()
{
	// with addition of buffers for 3x3 square mask
	// 8x8 original image is now 10x10
	int [][] imageSquare =                                      //12
	{ 
		{4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
		{4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
		{4, 4, 4, 4,48, 4, 4, 4, 4, 4},
		{4, 4, 4,64,64,64,64, 4, 4, 4},
		{4, 4,17,64,64,96,64, 4, 4, 4},
		{4, 4, 4,64,85,64,64, 8, 4, 4},
		{4, 4, 4,64,64,64,64, 4, 4, 4},
		{4, 4,56, 4, 4,23, 4, 4, 4, 4},
		{4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
		{4, 4, 4, 4, 4, 4, 4, 4, 4, 4}
	};

	// 3x3 square mask
	int [][] squareMask = 
	{
		{1, 1, 1},
		{1,-8, 1},
		{1, 1, 1}
	};

	int [][] resultSquare;
	resultSquare = new int [10][10];

	// just instantiating result arrays
	for(int i = 0; i < 10; i++){
		for(int j = 0; j< 10; j++){
			resultSquare [i][j] = 0;
		}
	}

	//now calculating for 3x3 squre mask
	int i,j,m,n,a,b;
	for(i = 1; i < 9; i++){        //starting from the original image array
		for(j = 1; j < 9; j++)
		{
			a = i-1;
			b = j-1;
			
			for(m = 0; m < 3; m++, a++){
				for(n = 0; n < 3; n++, b++)
				{
					resultSquare [a][b] = resultSquare [a][b] + imageSquare [a][b] - squareMask[m][n];
				}
			}

                  }
	}

	// print out the result 
	
}

the error that I’m getting is

comp.cpp:12: error: expected unqualified-id before '[' token

I googled but I’ve had not much luck with it. Would someone shed some light as to what I did wrong?

Понравилась статья? Поделить с друзьями:
  • Error expected unqualified id before return
  • Error expected unqualified id before public
  • Error expected unqualified id before numeric constant перевод
  • Error expected unqualified id before numeric constant ошибка
  • Error expected unqualified id before int