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

If you don't know how to interpret expected unqualified id error, read our article where our experts will uncover the steps needed to solve the failure.

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

  • Forum
  • Beginners
  • expected unqualified-id before ‘for’

expected unqualified-id before ‘for’

Hello! I have this code (I put just a part of it):

1
2
3
4
5
6
7
8
9
  class TMTrackAnalyzer : public edm::EDAnalyzer {
    public:
      # declare public stuff here
    private:
      # declare private stuff here
      for(int i=1;i<=10;i++){
        cout<<i;
      }
  };

And I get this error:
expected unqualified-id before ‘for’
for(int i=1;i<=10;i++){

What do I do wrong? Thank you!

The code needs to go into a method:

1
2
3
4
5
6
7
8
9
10
11
  class TMTrackAnalyzer : public edm::EDAnalyzer {
    public:
      # declare public stuff here
    private:
      void f() {
        # declare private stuff here
        for(int i=1;i<=10;i++){
          cout<<i;
        }
      }
  };

But in that for loop I want to declare some private members of the class. Where do I need to call that method later?

But in that for loop I want to declare some private members of the class

If you declare variables within the loop, they’re not private members of the class. They’re local to the scope of the loop. Given the code kbw posted, you have four different places you can declare variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class TMTrackAnalyzer : public edm::EDAnalyzer 
{
public:
    // 1. Declare public stuff here 
private:
      // 2. Declare private stuff here 
      void f() 
     {  // 3. Declare variables local to f() here
         for (int i=1; i<=10; i++)
        {  // 4. Declare variables local to the scope of the loop here
            cout<<i;
        }
     }
};

Where do I need to call that method later?

Where ever you want to output the numbers 1-10, which is what f() does.

Last edited on

I understand, but what I want is to declare private member of the class (no just of the loop), but they have a similar name:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for (unsigned int i = 0; i <= 75; i++) {                                                                                                
    const string tn = tnames[i];                                                                                                         
    const string en = enames[i];                                                                                                         
                                                                                                                                         
    map< ObjectType, TH1F*> hisNumInputStubs_[tn] ;                                                                                      
    map< ObjectType, TH1F*> hisQoverPtInputStubs_[tn];                                                                                   
    map< ObjectType, TH1F*> hisNumOutputStubs_[tn];                                                                                      
    map< ObjectType, TH1F*> hisNumStubsPerTrack_[tn];                                                                                    
    map< ObjectType, TH1F*> hisTrackQoverPt_[tn];                                                                                        
    map< ObjectType, TH1F*> hisTrackPurity_[tn];                                                                                         
    map< ObjectType, TH1F*> hisNumTPphysics_[tn];                                                                                        
    map< ObjectType, TH1F*> hisNumTPpileup_[tn];                                                                                         
    map< ObjectType, TH1F*> hisSumPtTPphysics_[tn];                                                                                      
    map< ObjectType, TH1F*> hisSumPtTPpileup_[tn];                                                                                       
  }

This is what I actually have. So how can I declare all these, without writing them one by one? Thank you!

I don’t understand you
¿what’s the purpose of the loop?

> map< ObjectType, TH1F*> hisNumInputStubs_[tn];
first, that’s an array declaration, so the brackets would set the size of the array.
but `tn’ is an string, not a number.

If you wanted to populate the map (with value nullptr), there should be no type before.
However, the key of your map is an `Objectype’, not a string.

To describe your problem better, please read this
https://blog.codinghorror.com/rubber-duck-problem-solving/

Topic archived. No new replies allowed.

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



Hi, I’m using Dev-C++ and I recently ran accross this error message that I can’t make heads or tails of. My code so far is:


int x=220;
int y=585;

for (int i=0;i<20;i++)
{
        for(int h=0;h<10;h++)
        {
              myGrid.grid[h].x=x;
              myGrid.grid[h].y=y;
              x+=20;
              }
              x=220;
              y+=20;
} 

The full error message I’m getting is:


expected unqualified-id before "for" 
expected `,' or `;' before "for" 
expected constructor, destructor, or type conversion before '<' token 
expected `,' or `;' before '<' token 
expected constructor, destructor, or type conversion before '++' token 
expected `,' or `;' before '++' token 

It looks like I’m missing a semicolon somewhere but I’m sure I’m not. I’ve been over this code for a good hour, changing it and whatnot but I haven’t been able to fix it.

It’ll probably just end up being a stupid mistake that I missed, but it’s always easier to have someone else’s eyes look at it.

Uh, that *is* inside a function, right? You can’t write «code» «at the top level» like that. You can only declare and initialize (not «assign to») globals, or write classes/functions/etc.

Yeah, its inside a function. Maybe this will be one of those things where if you ignore it for a while it’ll go away ;)

Is this a .cpp file or a .c file? I can’t remember for sure, since it’s been a while since I programmed in C, but there is (or at least used to be) a restriction where you had to define your local variables at the top of a block of code. I’m not sure if defining them within the initializer part of a for-statement would count as top of the block or not.

Just wild speculation. Given just that code, though, I can’t see anything that is obviously wrong, so wild speculation is all I have left. [smile]

One question: Is the error referring to the first for-statement, or the second? Also, did you copy-paste this code into GameDev, or re-type it? Sometimes small subtle mistakes can exist in the original, but when you re-type it to ask for help, you unknowingly fix the problem.

«We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves.» — John Locke

I Found it!!!

I should’ve showed you guys the 10 lines before this also, you guys probably would have caught it. I had a 4 nested if statements above it and at the end of them I accidently put 5 }’s, and the compiler took the last one as the one closing the function, putting this code out in the open which, like Zahlman, pointed out, throws the error.

Thanks for the help guys.

#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);
  }
}

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

Понравилась статья? Поделить с друзьями:
  • 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