Error expected unqualified id before return

  • Forum
  • Beginners
  • expected unqualified-id before return

expected unqualified-id before return

I’ve been racking my brain for the past hour or so trying to figure this code out. The goal is to build a code that will convert pounds to kilograms upon typing the pound variable.

I keep on getting the same error: expected unqualified-id before ‘return’

This is referring to the very end, where it says «return kilograms ;»

How might I go about getting rid of this error? What did I do wrong?

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
 #include<iostream>
using namespace std ;

float lbTokg ( float weightlb = 0 ) ;

int main()
{

float pounds, kilograms ;

cout << "Type wieght: t" ;
cin >> pounds ;

kilograms = lbTokg ( pounds ) ;

cout << pounds << " lb is equal to " << kilograms << "kg " ;

return 0 ;
 }


 
float lbTokg ( float pounds ) 
 {
  float kilograms ( pounds / 2.2046 ) ;
 } 
  return kilograms ;

You have a function which should return a value, but it doesn’t return anything:

1
2
3
4
float lbTokg ( float pounds ) 
{
    float kilograms ( pounds / 2.2046 ) ;
} 

and then, all alone by itself, you have this statement:
return kilograms ;

That statement needs to be moved so it is before the closing brace of the function:

1
2
3
4
5
float lbTokg ( float pounds ) 
{
    float kilograms ( pounds / 2.2046 ) ;  
    return kilograms ;
} 

Incidentally, the variable kilograms isn’t needed, you could just do this:

1
2
3
4
float lbTokg ( float pounds ) 
{
    return   pounds / 2.2046 ;  
} 

Thank you! That worked perfectly.

Topic archived. No new replies allowed.

Содержание

  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. Error expected unqualified id before returning
  32. ERROR: expected unqualified-id before ‘(‘ token #5787
  33. Comments
  34. Basic Infos
  35. Platform
  36. Settings in IDE
  37. Problem Description
  38. Debug Messages
  39. Temporary fix
  40. Footer

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] Про жизнь.

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

Источник

Error expected unqualified id before returning

Slight compile problems. I’m Linux using g++

Here’s what happens in terminal

john@john-laptop:/media/disk/Cannon$ make
g++ -Wall -O2 -c -o Enemy.o Enemy.cpp
Enemy.cpp:10: error: expected unqualified-id before ‘void’
Enemy.cpp:18: error: expected unqualified-id before ‘void’
Enemy.cpp:24: error: expected unqualified-id before ‘int’
Enemy.cpp:29: error: expected unqualified-id before ‘int’

make: *** [Enemy.o] Error 1

Here’s the source code for Enemy.cpp

Source for Enemy.h

and because this is related to stats i’ll throw that in too

and then there’s

Can someone help me solve this, I’ve been on google for about 2 hours now, and I can’t seem to figure this out. I have a feeling it’s the way my classes are setup, but .. I’m not so sure..

Thanks in advance!!

void ENEMY::createEnemy( char * name, int health, int money, int damage, int x, int y)

you always need to write the type of the return value in front of the class name, like you did in Stats.cpp.

Thanks for the help, I see where your going with this, but the problem has gotten a bit worse.

I’ve added the void onto the line. And I still have the above error messages, plus this one

Источник

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.

Источник

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:
struct {  // error, no name
   int bar;
};
  • a header file has a class or struct with a name already used inside ifndef, define statements
#ifndef foo
#define foo
#include <vector>

struct foo {  // error, foo already in use
   std::vector<int> bar;
};

#endif

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
int foo(int baf) { return baf; }
 
int bar(int foo) {
   foo = foo(4);
   return foo; 
}

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
class Foo {
public:
   int x;
};
 
class Bar {
public:
   Foo Maz() { return 0; }  // 0 is of type int, not Foo
};

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 had: 
foo operator<(const foo & f) const

// instead of:
bool operator<(const foo & f) const
  • you’re using an invalid argument for a conditional statement
string x = "foo";
if (x) cout << "true" << endl;

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
class Foo 
{
public:
   int bar;
   Foo(int x);
}; 
 
Foo::Foo(int x);  // semicolon ';' needs to be removed
{
   bar = x;
}

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
int foo(int bar)
{
   int bar;
   return bar;
}

‘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
ostream & os;  // instead of: std::ostream & os;
  • make sure you didn’t mistype the scope operator «::», e.g.: «name:name» instead of «name::name»
  • make sure you included the required libraries
#include <iostream>
// missing vector library include
class Foo {
public:      
   std::vector<int> Bar(std::vector<int> FooBar) { return FooBar; }
};
  • a header file is listed after a file that makes use of it in the include directives
// test.h file
#ifndef TEST_H_
#define TEST_H_
std::string bar;
#endif

// test.cpp file
#include "test.h"
#include <iostream>  // error, needed before test.h
using namespace std;

int main()
{
   cout << bar << endl;
   return 0;
}

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’
const int MAX = 10  // error

int main() {
   string foo;
   cout << foo.size();
   return 0;
}
  • possibly from a double namespace definition, or a fully-qualified (e.g., std::cout) name already under a ‘using’ directive
  • possible missing ‘<<‘ or ‘>>’ operator in a cin/cout statement
int foo = 0, bar = 0;
cin foo >> bar;  // should be: cin >> foo >> bar;

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

expected primary-expression before ‘int’
  • Message found in GCC version 4.5.1
    • in GCC version 3.2.3 reported as: parse error before ‘)’ token
  • one likely cause is using (or leaving in) a type name in a function call
int sum(int x, int y) { return (x + y); }

int main() {
   int a = 4, b = 5;
   sum(a, int b); // int is the problem causer
   return 0;
}

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
class Foo() {
public:
   int x;
};
  • expected unqualified-id before ‘return’
    • e.g.: missing opening brace in a conditional statement
int foo = 3, bar = 2;
if (foo > bar)  // error, no "{"
   cout << foo << endl;
}

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]’
char bar[10];
const char *foo = "ppp";
bar = *foo;  // error

// possible fix, use strcpy from the cstring header:
char bar[10];
const char *foo = "ppp";
strcpy(bar, foo);
  • improperly accessing elements of a 2D array
char foo[2][3];
foo[1] = ' '; // error, need both dimensions, eg: foo[1][0] = ' ';

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
char foo = 'f';
char bar[] = "bar";
if (strcmp(foo, bar) != 0)
   cout << "Correct answer!";
// strcmp was expecting 2 character pointers, foo doesn't qualify

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
// attempting to combine two C-strings
cout << "abc" + "def";

// possible fix: convert 1 argument to a string type
cout << "abc" + string("def");

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

invalid use of template-name ‘TEMPLATE’ without an argument list
  • Message found in GCC version 4.5.1
    • often paired with: expected unqualified-id before ‘TOKEN’
    • in GCC version 3.2.3 reported as: syntax error before ‘CHARACTER’ token
  • the type is missing after the class name in a function definition
template <class T> class Foo {
private:
   int x;
public:
   Foo();
};

template<class T> Foo::Foo() { x = 0; }  // error, should be: Foo<T>::Foo()

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’
// test.cpp
// file is missing iostream include directive
int main() {
   std::cout << "hello, world!n";
   return 0;
}

‘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
void foo(int x, vector y);
  • 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
class FooBar {
private: int bar;
public: friend void foo(FooBar & f);
};
void fooo(FooBar & f) {  // error
   f.bar = 0;
}
  • 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
class Foo {
private: Foo() {}
public: Foo(int Num) {}
};
class Bar : public Foo {
public: Bar() {}
// Bar() implicitly accesses Foo's private constructor
};
solution 1: use an initializer list to bypass implicit initialization
solution 2: make the accessed base class member protected instead of private
  • You’re trying to initialize a contained class member by accessing private data
class Foo {
private: char mrStr[5];
public: Foo(const char *s = "blah") { strcpy(mrStr, s); }
};

class Bar {
private:
   int mrNum;
   Foo aFoo;
public:
   Bar(int n, const Foo &f);
};

// error, attempting to use the Foo class constructor by accessing private data:
Bar::Bar(int n, const Foo &f) : aFoo(f.mrStr) {  // mrStr is private
   mrNum = n;
}

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

Bar::Bar(int n, const Foo &f) : aFoo(f) {
   mrNum = n;
}

ISO C++ forbids declaration of ‘FUNCTION’ with no type[edit | edit source]

  • Message found in GCC version 3.2.3, 4.5.1
  • you’ve created a function with no listed return type
Foo() { return 0: }
// should be: int Foo() { return 0: }

multiple definitions of[edit | edit source]

eg: multiple definition of `main’
  • Message found in GCC version 4.5.1
  • check for missing inclusion guard in header file
  • check for duplicate file listing in compile commands / makefile
    • e.g.: g++ -o foo foo.cpp foo.cpp
  • check for definitions rather than only declarations in the header file

‘CLASS FUNCTION(ARGUMENTS)’ must have an argument of class or enumerated type[edit | edit source]

  • Message found in GCC versions 3.2.3, 4.5.1
  • you’re attempting to access members of a class with a non-member function
    • non-member functions must access class members explicitly
eg: CLASS_NAME FUNCTION_NAME(CLASS_NAME OBJECT_NAME, ARGUMENTS)
  • you’re redefining an operator for a standard (built-in) type
class Foo {
public:
   friend int operator+(int x, int y);
};

new types may not be defined in a return type[edit | edit source]

  • Message found in GCC version 4.5.1
    • in GCC version 3.2.3, reported as:
semicolon missing after definition of ‘CLASS’
ISO C++ forbids defining types within return type
  • check for a missing semicolon at the end of a class definition
class Foo {
public:
   int x;
}  // Error

no match for call to ‘FUNCTION’[edit | edit source]

  • Message found in GCC versions 3.2.3, 4.5.1
  • make sure the function’s namespace is used ( using namespace std / std::function() )
  • make sure the function name is not misspelled, parentheses aren’t missing
  • make sure the function is called with the correct arguments / types / class
  • if you’re initializing a variable via parentheses, if there’s underscores in the variable name try removing them. Sometimes an equals sign is the only way…
  • you’re using the same name for a variable and a function within the same namespace
string bar() {
   string foo = "blah";
   return foo;
}

int main() {
   string bar;
   bar = bar();  // error, "bar()" was hidden by string initialization
   return 0;
}

no matching function for call to ‘FUNCTION’[edit | edit source]

  • Message found in GCC version 4.5.1
  • make sure there aren’t parentheses where there shouldn’t be (e.g.: classname::value() instead of classname::value )
  • you’re using a string argument with a function that expects a C-string
// broken code
ifstream in;
string MrString = "file.txt";
in.open(MrString);

// solution: convert the string to a C-string
ifstream in;
string MrString = "file.txt";
in.open(MrString.c_str());

non-constant ‘VARIABLE’ cannot be used as template argument[edit | edit source]

  • Message found in GCC version 3.2.3
    • in GCC version 4.5.1 reported as: ‘VARIABLE’ cannot appear in a constant-expression
  • variable used for a template argument, which are required to be constant at compile time
template <class T, int num>
class Bar {
private:
   T Foo[num];
};

int main() {
   int woz = 8;
   Bar<double, woz> Zed;  // error, woz is not a constant
   return 0;
}

non-member function ‘FUNCTION’ cannot have cv-qualifier[edit | edit source]

error: non-member function ‘int Foo()’ cannot have cv-qualifier

cv = constant / volatile
  • Message found in GCC version 4.5.1
  • you’re using the ‘post’ const (constant value) on a non-member function
  • you’re not using the scope qualifier («TYPENAME::») in the function definition
  • you mistyped the definition for a template class’s member function
template<class Type>
class Foo {
private:
   int stuff;
public:
   int bar() const;
};

template<class Type>
int Foo::bar() const {  // error
   return stuff;
}

possible fix:

template<class Type>
int Foo<Type>::bar() const {
   return stuff;
}

passing ‘const OBJECT’ as ‘this’ argument of ‘FUNCTION’ discards qualifiers[edit | edit source]

  • Message found in GCC version 4.5.1
  • you’re returning an address
  • you’re attempting to access a container element with a const_iterator using a member function that has no non-const versions. The non-const function does not guarantee it will not alter the data

request for member ‘NAME’ in ‘NAME’, which is of non-class type ‘CLASS’[edit | edit source]

  • Message found in GCC versions 4.5.1
    • in GCC version 3.2.3 reported as:
request for member ‘NAME’ in ‘NAME’, which is of non-aggregate type ‘TYPE’
  • check the function call in the code, it might be calling a function with incorrect arguments or it might have misplaced/missing parenthesis
  • your using the «*this» pointer where you should just be using the functions name
  • e.g., use: return mem_func(); instead of: return *this.mem_func();
  • using the «*this» pointer with the wrong syntax
class Foo {
public:
   int x;
   Foo(int num = 0) { x = num; }
   void newX(int num);
};

void Foo::newX(int num) {
   *this.newX(num);  // error, need (*this).newX or this->newX
}

statement cannot resolve address of overloaded function[edit | edit source]

  • Message found in GCC versions 3.2.3, 4.5.1
  • make sure you’re not forgetting the parenthesis after a member function name
class Foo {
public:
   int Bar() { return 0; }
};

int main() {
   Foo x;
   x.Bar;  // error
   return 0;
}

two or more data types in declaration of ‘NAME’[edit | edit source]

  • Message found in GCC version 4.5.1
    • in GCC version 3.2.3 reported as: extraneous ‘TYPE’ ignored
  • you have multiple data types listed for a function declaration’s return value
int char sum(int x, int y);  // int char
  • possibly a missing semicolon in between 2 type declarations
    • usually missing in a function, struct, or class declaration after the curly braces {}

<GOBBLEDEGOOK> undefined reference to <GOBBLEDEGOOK>[edit | edit source]

  • Message found in GCC version 4.5.1
    • in GCC versions 4.0.1, 4.2.1 reported as: Undefined symbols
  • check for a missing or mistyped header includes
  • check for a missing or mistyped files/libraries in a project/make file
  • check for a missing, mistyped, or undefined functions or class constructors
// header file
void foo();
void bar();
void baz();

// implementation file, bar definition is missing
void foo() { cout << "foon"; }
void baz() { cout << "bazn"; }
  • check for function declarations that do not match their definitions
  • make sure function names do not overlap those in existing header files
  • make sure compile commands syntax / makefile structure is correct (e.g.: g++ -o file.cc … etc.)
  • no main() function is defined in any of the files inside a project/makefile
    • e.g.: undefined reference to `WinMain@16′

‘NAME’ was not declared in this scope[edit | edit source]

  • Message found in GCC version 4.5.1
    • in GCC versions 3.2.3 reported as: ‘FUNCTION’ undeclared (first use of this function)
  • look for a misspelled or changed variable/function/header call name
lonh wait;

// instead of:
long wait;
  • make sure the proper header and library files are included
    • defined variables may need the headers they utilize included in all files that use the defined variables

Tiami

Яростный кот

43 / 1 / 0

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

Сообщений: 220

1

20.03.2009, 09:59. Показов 61018. Ответов 14

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


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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <iostream>
using namespace std;
enum {researsher,laborer,secratary,manager,accountant,executive};
int main()
{
    char a='a';
    cout<<"Vvedite 6ykBy Dol>I<HOCTU(researsher,laborer,secratary,manager,accountant,executive)=";
    cin>>a;
    getchar();
    switch(a)
{
             case 'a':
                  cout<<"accountant";
                  break;
             case 'l':
                  cout<<"laborer";
                  break;
             case 's':
                  cout<<"secretary";
                  break;
             case 'm':
                  cout<<"manager";
                  break;
             case 'e':
                  cout<<"executive";
                  break;
             case 'r':
                  cout<<"researcher";
                  break;
}
getchar();
return 0;
}
struct employe
{       
    int number;       
    float money;
};
{    
    employe nomer;    
    employe many;    
    employe sanka;    
    char ch='a';    
Label:    
      cout<<"Vvedite Dannie Sotrudnika 1(Nmber,Money)=rn";    
      cin>>nomer.number>>nomer.money;    
      cout<<"Vvedite Dannie Sotrudnika 2(Nmber,Money)=rn";    
      cin>>many.number>>many.money;    
      cout<<"Vvedite Dannie Sotrudnika 3(Nmber,Money)=rn";    
      cin>>sanka.number>>sanka.money;     
      getchar();
      cout<<"Spasibo,Enter na Monitor,prodol>I<it' Y/N?";    
      cin>>ch;    
      if(ch='y')
      {    
          cout<<"sotrudnik(Number,Money)"<<nomer.number<<" "<<nomer.money<<endl;    
          cout<<"sotrudnik(Number,Money)"<<many.number<<" "<<many.money<<endl;    
          cout<<"sotrudnik(Number,Money)"<<sanka.number<<" "<<sanka.money<<endl;
      }    
      else 
      {
          if(ch='n')    
              return 0;
      }
      if(nomer.number == many.number||
          many.number  == sanka.number||
          sanka.number == nomer.number)
      {    
          cout<<"Error,prodolgit Y/N ?";    
          cin>>ch;   
          if(ch='y')    
              goto Label;    
          else 
              if(ch='n')    
                  return 0;
      }    
      else 
      {
          if(nomer.number<0||many.number<0||sanka.number<0)    
              return 0;
      }
     getchar();    
      return 0;
}
struct dates
{
       int  den;
       int  mec;
       int  god;
       char gen;
};
{
    dates mur;
    dates mars;
    dates mir;
    dates a;
    cout<<"Vveidte den' mec9Ic God=";
    cin>>mur.den>>a.gen>>mars.mec>>a.gen>>mir.god;
    getchar();
    cout<<"Vasha Data="<<mur.den<<"/"<<mars.mec<<"/"<<mir.god;
    getchar();
    return 0;
}
{
    cout<<"Vasha dolgnost="<<a<<endl;
    cout<<"Data registracii"<<mur.den<<"/"<<mars.mec<<"/"<<mir.god<<endl;
    cout<<"sotrudnik(Number,Money)"<<nomer.number<<" "<<nomer.money<<endl;    
    cout<<"sotrudnik(Number,Money)"<<many.number<<" "<<many.money<<endl;    
    cout<<"sotrudnik(Number,Money)"<<sanka.number<<" "<<sanka.money<<endl;
    getchar();
    return 0;
}

Пишет ошибки:
1.expected unqualified-id before ‘{‘ token <<39 строка
2.expected `,’ or `;’ before ‘{‘ token <<39 строка
3.expected unqualified-id before ‘{‘ token <<92 строка
4.expected `,’ or `;’ before ‘{‘ token <<92 строка
5.expected unqualified-id before ‘{‘ token <<104 строка
6.expected `,’ or `;’ before ‘{‘ token <<104 строка

Исправьте как нада и подскажите почему неправильно?
return можно и убрать для обьединения программы,подскажие как лучше обьединить создав 1 программу

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



0



1507 / 774 / 103

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

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

20.03.2009, 10:04

2

Помести все в блок функции main() { } и убирите лишние кавычки.



1



Яростный кот

43 / 1 / 0

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

Сообщений: 220

20.03.2009, 10:09

 [ТС]

3

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

Помести все в блок функции main() { } и убирите лишние кавычки.

Так и думал,но все таки спасибо)

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

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

Помести все в блок функции main() { } и убирите лишние кавычки.

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



0



98 / 54 / 3

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

Сообщений: 273

20.03.2009, 10:14

4

Значит так:

В строке 33 ты закрыл функцию main. Далее идет объявление структуры. Там всё верно. А в строке 39 какая-то неопознанная открывающаяся скобка {. И тоже самое в 92 и 104. С закрывающимися скобками тоже самое. Плюс еще, ты совершаешь различные действия вне какой бы то ни было функции (всё что после строки 33)
Проще сказать, как должно быть:
Все структуры объявляешь ДО функции main. А все свои операции — ВНУТРИ main.

Добавлено через 2 минуты 52 секунды
Лишние скобки тут: 33, 39, 84, 92, 104, 103. Плюс, нужно поубирать лишние «getchar(); return 0;», за исключением строки 111, а все объявления структур перенести наверх перед main



0



Яростный кот

43 / 1 / 0

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

Сообщений: 220

20.03.2009, 10:17

 [ТС]

5

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

Значит так:

В строке 33 ты закрыл функцию main. Далее идет объявление структуры. Там всё верно. А в строке 39 какая-то неопознанная открывающаяся скобка {. И тоже самое в 92 и 104. С закрывающимися скобками тоже самое. Плюс еще, ты совершаешь различные действия вне какой бы то ни было функции (всё что после строки 33)
Проще сказать, как должно быть:
Все структуры объявляешь ДО функции main. А все свои операции — ВНУТРИ main.

Приведи готовый листинг если не трудно



0



Deicider

98 / 54 / 3

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

Сообщений: 273

20.03.2009, 10:27

6

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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <iostream>
using namespace std;
enum {researsher,laborer,secratary,manager,accountant,executive};
 
struct employe
{       
    int number;       
    float money;
};
 
struct dates
{
       int  den;
       int  mec;
       int  god;
       char gen;
};
 
 
int main()
{
    char a='a';
    cout<<"Vvedite 6ykBy Dol>I<HOCTU(researsher,laborer,secratary,manager,accountant,executive)=";
    cin>>a;
    getchar();
    switch(a)
{
             case 'a':
                  cout<<"accountant";
                  break;
             case 'l':
                  cout<<"laborer";
                  break;
             case 's':
                  cout<<"secretary";
                  break;
             case 'm':
                  cout<<"manager";
                  break;
             case 'e':
                  cout<<"executive";
                  break;
             case 'r':
                  cout<<"researcher";
                  break;
}
 
    
    employe nomer;    
    employe many;    
    employe sanka;    
    char ch='a';    
Label:    
      cout<<"Vvedite Dannie Sotrudnika 1(Nmber,Money)=rn";    
      cin>>nomer.number>>nomer.money;    
      cout<<"Vvedite Dannie Sotrudnika 2(Nmber,Money)=rn";    
      cin>>many.number>>many.money;    
      cout<<"Vvedite Dannie Sotrudnika 3(Nmber,Money)=rn";    
      cin>>sanka.number>>sanka.money;     
      getchar();
      cout<<"Spasibo,Enter na Monitor,prodol>I<it' Y/N?";    
      cin>>ch;    
      if(ch='y')
      {    
          cout<<"sotrudnik(Number,Money)"<<nomer.number<<" "<<nomer.money<<endl;    
          cout<<"sotrudnik(Number,Money)"<<many.number<<" "<<many.money<<endl;    
          cout<<"sotrudnik(Number,Money)"<<sanka.number<<" "<<sanka.money<<endl;
      }    
      else 
      {
          if(ch='n')    
              return 0;
      }
      if(nomer.number == many.number||
          many.number  == sanka.number||
          sanka.number == nomer.number)
      {    
          cout<<"Error,prodolgit Y/N ?";    
          cin>>ch;   
          if(ch='y')    
              goto Label;    
          else 
              if(ch='n')    
                  return 0;
      }    
      else 
      {
          if(nomer.number<0||many.number<0||sanka.number<0)    
              return 0;
      }
 
    dates mur;
    dates mars;
    dates mir;
    dates a;
    cout<<"Vveidte den' mec9Ic God=";
    cin>>mur.den>>a.gen>>mars.mec>>a.gen>>mir.god;
    getchar();
    cout<<"Vasha Data="<<mur.den<<"/"<<mars.mec<<"/"<<mir.god;
 
    cout<<"Vasha dolgnost="<<a<<endl;
    cout<<"Data registracii"<<mur.den<<"/"<<mars.mec<<"/"<<mir.god<<endl;
    cout<<"sotrudnik(Number,Money)"<<nomer.number<<" "<<nomer.money<<endl;    
    cout<<"sotrudnik(Number,Money)"<<many.number<<" "<<many.money<<endl;    
    cout<<"sotrudnik(Number,Money)"<<sanka.number<<" "<<sanka.money<<endl;
 
    getchar();
    return 0;
}

Добавлено через 4 минуты 24 секунды
И еще: использование goto это не есть хороший стиль программирования. Конечно, программа работает, но нужно использовать функционал языка для достижения не только конечного результата, но и удобства программирования и последующей модификации программы, а с goto каши не сваришь. Ну это так, на философию потянуло )))



1



Яростный кот

43 / 1 / 0

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

Сообщений: 220

20.03.2009, 10:45

 [ТС]

7

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

И еще: использование goto это не есть хороший стиль программирования. Конечно, программа работает, но нужно использовать функционал языка для достижения не только конечного результата, но и удобства программирования и последующей модификации программы, а с goto каши не сваришь. Ну это так, на философию потянуло )))

Ага спасибо,я просто кроме goto пока что ничего не знаю учусь всего недельку две

Добавлено через 11 минут 19 секунд
Возникли Ошибки
1.conflicting declaration ‘dates a’ <<89 строка
2.‘a’ has a previous declaration as `char a’ <<19 строка
3.declaration of `dates a’ <<89 строка
4.conflicts with previous declaration `char a’ <<19 строка
5.`gen’ has not been declared <<91 строка
6.request for member of non-aggregate type before ‘>>’ token <<91 строка
7.`gen’ has not been declared <<91 строка
8.request for member of non-aggregate type before ‘>>’ token <<91 строка



0



Супер-модератор

8781 / 2532 / 144

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

Сообщений: 11,873

20.03.2009, 10:52

8

Tiami, у тебя переменная А объявлена дважды, как char,и как dates… остальные ошибки могут исчезнуть вполне, если поправишь эту…



1



Tiami

Яростный кот

43 / 1 / 0

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

Сообщений: 220

20.03.2009, 11:12

 [ТС]

9

Исправил тока как в цикле switch ?вывести в последнем абзаце должность?

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
94
95
96
97
98
99
100
#include <iostream>
using namespace std;
enum {researsher,laborer,secratary,manager,accountant,executive};
struct employe
{       
    int number;       
    float money;
};
struct dates
{
       int  den;
       int  mec;
       int  god;
       char gen;
};
int main()
{
    char b='a';
    cout<<"Vvedite 6ykBy Dol>I<HOCTU(researsher,laborer,secratary,manager,accountant,executive)=";
    cin>>b;
    getchar();
    switch(b)
{
             case 'a':
                  cout<<"accountant";
                  break;
             case 'l':
                  cout<<"laborer";
                  break;
             case 's':
                  cout<<"secretary";
                  break;
             case 'm':
                  cout<<"manager";
                  break;
             case 'e':
                  cout<<"executive";
                  break;
             case 'r':
                  cout<<"researcher";
                  break;
}
    employe nomer;    
    employe many;    
    employe sanka;    
    char ch='a';    
Label:    
      cout<<"Vvedite Dannie Sotrudnika 1(Nmber,Money)=rn";    
      cin>>nomer.number>>nomer.money;    
      cout<<"Vvedite Dannie Sotrudnika 2(Nmber,Money)=rn";    
      cin>>many.number>>many.money;    
      cout<<"Vvedite Dannie Sotrudnika 3(Nmber,Money)=rn";    
      cin>>sanka.number>>sanka.money;     
      getchar();
      cout<<"Spasibo,Enter na Monitor,prodol>I<it' Y/N?";    
      cin>>ch;    
      if(ch='y')
      {    
          cout<<"sotrudnik(Number,Money)"<<nomer.number<<" "<<nomer.money<<endl;    
          cout<<"sotrudnik(Number,Money)"<<many.number<<" "<<many.money<<endl;    
          cout<<"sotrudnik(Number,Money)"<<sanka.number<<" "<<sanka.money<<endl;
      }    
      else 
      {
          if(ch='n')    
              return 0;
      }
      if(nomer.number == many.number||
          many.number  == sanka.number||
          sanka.number == nomer.number)
      {    
          cout<<"Error,prodolgit Y/N ?";    
          cin>>ch;   
          if(ch='y')    
              goto Label;    
          else 
              if(ch='n')    
                  return 0;
      }    
      else 
      {
          if(nomer.number<0||many.number<0||sanka.number<0)    
              return 0;
      }
    dates mur;
    dates mars;
    dates mir;
    dates c;
    cout<<"Vveidte den' mec9Ic God=";
    cin>>mur.den>>c.gen>>mars.mec>>c.gen>>mir.god;
    getchar();
    cout<<"Vasha Data="<<mur.den<<"/"<<mars.mec<<"/"<<mir.god<<endl;
    cout<<"Vasha dolgnost="<<b<<endl; //вот тут как?<<<<<<<<<<<<<<<<<<<<<<выводится просто буква,а не должность
    cout<<"Data registracii="<<mur.den<<"/"<<mars.mec<<"/"<<mir.god<<endl;
    cout<<"sotrudnik(Number,Money)"<<nomer.number<<" "<<nomer.money<<endl;    
    cout<<"sotrudnik(Number,Money)"<<many.number<<" "<<many.money<<endl;    
    cout<<"sotrudnik(Number,Money)"<<sanka.number<<" "<<sanka.money<<endl;
    getchar();
    return 0;
}

Добавлено через 7 минут 7 секунд

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

cout<<«Vasha dolgnost=»<<b<<endl; //вот тут как?<<<<<<<<<<<<<<<<<<<<<<выводится просто буква,а не должность

Как присвоить значение извлекаемое из цикла switch я просто не знаю



0



Lord_Voodoo

Супер-модератор

8781 / 2532 / 144

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

Сообщений: 11,873

20.03.2009, 11:22

10

Tiami, ты свой свитч с должностями перенеси в функцию, тогда код будет выглядеть примерно так

C++
1
cout<<"Vasha dolgnost="<<getDolgnost(b)<<endl;

что-то вроде такого:

C++
1
2
3
4
5
6
7
8
9
10
char* getDolgnost(char b){   
switch(b)
{
case'a':return "accountant";                              
case 'l':return "laborer";
case 's':return "secretary";
case 'm':return "manager";
case 'e':return "executive";
case 'r':return "researcher";
}



0



Яростный кот

43 / 1 / 0

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

Сообщений: 220

20.03.2009, 11:29

 [ТС]

11

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

что-то вроде такого:

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



0



Супер-модератор

8781 / 2532 / 144

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

Сообщений: 11,873

20.03.2009, 11:32

12

Tiami, а зачем? главное — решить задачу… просто твой код, мягко говоря, непонятно по каким соображениям разработчика должен выводить вместо буквы специальность, я так и не понял



0



Яростный кот

43 / 1 / 0

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

Сообщений: 220

20.03.2009, 11:39

 [ТС]

13

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

Tiami, а зачем? главное — решить задачу… просто твой код, мягко говоря, непонятно по каким соображениям разработчика должен выводить вместо буквы специальность, я так и не понял

Да я думал из цикла switch в памяти как бы сохранится переменная b,и она заменится в последнем абзаце на вид b=manager,напримерОказывается так незя)



0



Супер-модератор

8781 / 2532 / 144

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

Сообщений: 11,873

20.03.2009, 11:47

14

слушай, начинай читать следующую главу и юзай функции, так будем всем проще)))



1



Яростный кот

43 / 1 / 0

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

Сообщений: 220

20.03.2009, 13:40

 [ТС]

15

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

слушай, начинай читать следующую главу и юзай функции, так будем всем проще)))

Есть СерПосмотрите на моего кота и вы сразу поймете что приказ ИсполненОн кричит Есть СЕр!!и Лапу убирает вниз(Шутка



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

На чтение 2 мин. Просмотров 19 Опубликовано 15.12.2019

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

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

когда я его скомпилировал, я получил много ошибок.

Помогите мне, пожалуйста.

Содержание

  1. Решение
  2. 2 Answers 2
  3. Not the answer you’re looking for? Browse other questions tagged c++ or ask your own question.
  4. Related
  5. Hot Network Questions

Решение

Вы пропустили скобки, которые отмечают main() как функция:

Обратите внимание, что гораздо проще понять пространства имен, если вы явно используете std::cout а также std::endl скорее, чем using весь namespace std (что может привести вас в замешательство, если вы не знаете, что происходит). В качестве альтернативы, по крайней мере, должно быть понятно using :

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

Not the answer you’re looking for? Browse other questions tagged c++ or ask your own question.

Hot Network Questions

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

site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 4.0 with attribution required. rev 2019.11.15.35459

I’ve been working on a decryption program for another encryption program I made. It isn’t finished, and when I try to compile it to test it, it gives me the error «expected unqualified-id before ‘return'» right at the line where «return 0;» is. I am using Xcode for mac os, which is the same as g++ 4.0 for Unix/Linux. I can’t seem to figure this out, and I can’t test anything until it’s fixed.

Any ideas?

Here’s the code:
————————
#include <iostream>
#include <fstream>
#include <cstdio>
#include <bitset>
using namespace std;

int main () {

char password[32];
char file[100];
char filedata[8448];
bool filebin[8448];
bool key[32][8];
bool splitholder[1056][8];
int length;
int totiterations;
int iteration = 1;
bool passwordbin[32][8];
bool holder[32][1024][8];

//Get information from user
cout << «Type in the name and location of the .spir file you wish to decode.n»;
cin >> file;
fstream inputfile;
inputfile.open(file, ios::in | ios::binary);
while(inputfile >> filedata)
// cout << filedata;
inputfile.close();
//cout << «nn»;
int a = 0; /*Convert data from file into binary*/
while(a<8448){
if(!filedata[a]){
break;
}
if(filedata[a]==’0′){
filebin[a]=false;
}
else
{
filebin[a]=true;
}
// cout << filebin[a];
a++;
}
cout << «nn»;
cout << «nnType in the password for the file.»;
cin >> password;
length = strlen(password);

//Split the file into bytes
int b = 0,c = 0;
while(b<1056){
if(!filedata[b*8]){
break;
}
c = 0;
while(c<8){
splitholder[b][c] = filebin[(b*8)+c];
// cout << splitholder[b][c];
c++;
}
b++;
// cout << «n»;
}

//Separate the key from the file

//cout << length << «nn»;
b = 0;
while(b<length){
c = 0;
while(c<8){
key[b][c] = splitholder[b][c];
// cout << key[b][c];
c++;
}
b++;
cout << «n»;
}

//Shift the file to cover key
b = 0;
while(b<1024){
c = 0;
while(c<8){
splitholder[b][c] = splitholder[b+length][c+length];
// cout << key[b][c];
c++;
}
b++;
cout << «n»;
}

//Erase extra data

b = 1024;
while(b<1056){
c = 0;
while(c<8){
splitholder[b][c] = false;
c++;
}
b++;
cout << «n»;
}

//Convert the password into binary
int p = 0;
int e = 0;
while(e<length){
int f = 0;
while(e<8){
++ e;
if((password[p]&(1 << e) ? ‘1’ : ‘0’)==’1′){
passwordbin[p][e]=true;
}else{
passwordbin[p][e]=false;
}
f++;
cout << passwordbin[p][e];
}
p++;
}

//Decode the key
bool d,o;
b = 0;
while(b<length){
c = 0;
while(c<8){
d = key[b][c];
o = passwordbin[b][c];
key[b][c] = (d||o)&&!(d&&o);
c++;
}
b++;
}

//Decrypt the message
totiterations = length;
int f = 0,g = 0;
bool x,y,z;
while(iteration<totiterations){
f = 0;
while(f<1024)
g = 0;
while(g<8){
if(iteration = 0){
holder[iteration][f][g] = splitholder[f][g];
}
if(f=0){
y=holder[iteration][f][g];
x=key[iteration][g];
z=(x||y)&&!(x&&y);
holder[iteration+1][f][g] = x;
holder[iteration+1][f+1][g] = z;
}
else{
y=holder[iteration][f][g];
x=holder[iteration+1][f][g];
z=(x||y)&&!(x&&y);
holder[iteration+1][f+1][g] = z;
}
g++;
}
f++;
}
iteration++;
}

//end the program
return 0;
}
————————

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