Error expected initializer before class

When I compile the program I am working on I get: expected initializer before 'class' error in my Class.h file. I looked up the error message on the internet, but couldn't find the exact error,

Most likely, in the header file you include immediately before class.h, you’ll have something like:

class xyzzy {
    int plugh;
}

without the closing semi-colon. That will make your code sequence:

class xyzzy {
    int plugh;
}
class Account
{
    public:
    double dAccountBalance;

    double dAccountChange(double dChange);
};

which is clearly invalid. Inserting a semi-colon in class.h before the first line will fix it, but it’s clearly the wrong place to put it (since it means every header file you include immediately after that one would need a starting semicolon — also, it’s part of the definition in the first header and should be there).

Now that may not be the exact code sequence but it will be something very similar, and the underlying reason will be a missing piece of text in the previous header.

You should go back and put it in the earlier include file.

For example, consider:

include1.h:
    class xyzzy {
        int plugh;
    }
include2.h:
    class twisty {
        int little_passages;
    };
main.cpp:
    #include "include1.h"
    #include "include2.h"
    int main (void) {
        return 0;
    }

Compiling this produces:

include2.h:3: error: multiple types in one declaration

but placing the semicolon at the end of include1.h (or start of include2.h though we’ve already established that’s not a good idea) will fix it.

Содержание

  1. Error expected initializer before class
  2. Error expected initializer before class
  3. Error expected initializer before class
  4. Error expected initializer before class

Error expected initializer before class

I’m writing a class with an array and I’m supposed to calculate the average of some entered grades outside the class and in the main but I get the error
Expected Initializer before ‘.’ token

I’m not to sure what to do or i even did the class right
Please help!

What if I promised you $1000, but then just walk away, leaving you empty handed?
You make a promise on line 24, but you don’t keep it.

The error is on line 44. Please explain this code:
float gradeAverage.getGrade();

Line 44 looks like a nice prototype, but what is it doing in the middle of the program?

In the function «getGrade()» Why are you printing the array when you should be returning something from the array. In this case the «getGrade()» function should have a parameter the represents the element of the array that you need.

As you have it «float getGrade ()» would be better named «void printGrades ()».

Hope that helps,

I know that i shouldn’t be printing the there but the question was my teacher gave me was this
Write a class called Student that contains a property called grades that can store a
maximum of 10 grades. Create a setter and a getter method. The setter method
will take no parameters and return no parameters. Instead, within the setter
method you must construct a loop that will ask the user to enter 10 grades. The
getter method will simply print the 10 grades; so, it will take no and return no
parameters. Yes, that is a misnomer; this is because passing and returning arrays
has not been covered yet. Create another method called computeAverage that
return the average of all the grades. Create another method called
minimumGrade that returns the minimum grade the student received.

He knows it’s a misnomer but he wants us to do it anyway.
He hasn’t covered it yet so I was just looking it up but nothing I find helps

Now that I see what is required I will take a look tomorrow and see what I can do.

Источник

Error expected initializer before class

Here’s the rest of the code

That’s in a header file

Ok I see you are using the assignment operator for the copy constructor, that works but i would prefer the copy ctor

There is also a leak here..

Also at the very bottom of your header is What is that there for?

remove and from your Vector.hpp and add them to Vector.h file after

So compiler should not have problem with your codes, but your codes still have a lot of bugs, which
must be fixed.

Now, another problem arise: the compiler says: » [Linker error] undefined reference to `WinMain@16′ «. What should that mean?

That means you’ve chosen to build the app as a Windows app. You need to change it to a Console app in the Linker section somewhere.

If Vector.hpp has the function defs for Vector.h, Vector.hpp should be including Vector.h not the other way around.

To fix the memory leak you need to check if that pointer is already pointing to data, if so then free the memory, then allocate memory.

@clanmjc
clanmjc said

If Vector.hpp has the function defs for Vector.h, Vector.hpp should be including Vector.h not the other way around.

Vector.hpp implements the class-methods, it must not include the vector.h file. On the contrary vector.h must include Vector.hpp , because it is not a source file, not a *.cpp file. That is one of the three ways you may implement Template Class Methods

In your application file you have to include vector.h , tha is all

Источник

Error expected initializer before class

I am trying to make a calculator program and I am getting an error when I try to define a function from a class template

I get an error here:

template void Calculator ::set_operand_one()

You have variables mOperand1 etc but the constructor has operand1 etc — the spelling difference is part of what the compiler is complaining about.

You’ll need this include for vector.
#include

Edit:
See this earlier answer about initializing a static variable.
http://www.cplusplus.com/forum/beginner/100701/

I don’t think anyone is understanding.

The problem is not in the constructor, it is here:

void Calculator ::set_operand_one(T op1)

it gives an error: expected initializer before ‘

I copied and pasted your code into the compiler on this site and got those errors.

The class declaration is usually in the .h file. The class function definitions are usually in the .cpp file. You seem to have reversed these above.

Thank you everyone for your replies, but I finally figured out the problem.

I accidentally put the declaration of the class in the .cpp file and the definition in the .h file, when it should be the reverse of that! I apologize for making this stupid mistake. I will mark this thread as solved for others that make the same mistake 🙂

Источник

Error expected initializer before class

I keep receiving this error, nothing I do helps it’s in
line 11, while (again == ‘Y’ || again == ‘Y’) //begins while loop

You do have something essential missing, the braces around the body of the function.
See: http://www.cplusplus.com/doc/tutorial/program_structure/

Once you have followed that advice you will get a different error: What is the «again»?

PS. Please edit your post to use code tags.
See: http://www.cplusplus.com/articles/jEywvCM9/
Pay attention to indentation too. It can help reading your code.

When I put a brace < before the while statement I end up with a 10 more errors?
This is my first programming class I have never done anything like this and I’m frustrated.

These are the instruction for the program, I have to include all of this and I don’t even know if I have included all of it.

Create the following program which converts Fahrenheit to Celsius. Your program must have the following functions:
•Read integer Fahrenheit temperatures from the user. You need to check whether the input is the correct one or not. If the user enters the incorrect number, ask it again.
•Use the formula: Celsius = (Fahrenheit – 32) * 5.0 / 9.0
•The output Celsius should be a floating point with two digits of precision.
•The Celsius temperatures should be displayed with a sign of positive or negative.
•The program should ask the user to continue or not. If the user wants to do the conversion again, use repetitive statements such as DO WHILE, FOR, or IF THEN ELSE to do the conversion again.
•Add comments to explain the functions of the program.

I have been working on this and this is what I now have, with a set of new errors.
which are [Error] ‘setprecision’ cannot be used as a function
and [Error] ‘setw’ cannot be used as a function

Hi dreaweiss, welcome to the forum.

I’ll outline the problems with your code:

1.) On line 4, you declare three variables. Two of them, namely ‘setprecision’ and ‘setw’ are also the names of functions found in the ‘std’ namespace. Normally, one would access these functions by using the scope-resolution operator like so: std::setprecision and std::setw . However, since you’ve elected to use using namespace std; in global scope, the compiler thinks that your function calls on lines 28 and 30 are actually attempts to treat your variables on line 4 as functions.

The way to fix this is to simply remove the offending variables on line 4, since you aren’t even using them for anything. Your fourth line of code should therefore only declare ‘again’.

2.) Technically, line 4 shouldn’t just declare ‘again’, but also define / initialize it. If you do not give ‘again’ an initial value, you’re invoking undefined behavior on line 5 when you enter the while-loop because ‘again’ contains garbage, and you’re attempting to access it. Fix this by initializing ‘again’ on line 4 (so that it may enter the while-loop).

In addition, ‘again’ shouldn’t be an int , it should be a char .

3.) There’s a discrepancy in the condition of your while-loop on line 5. What you probably meant to write was while (again == ‘y’ || again == ‘Y’ ) , not while (again == ‘Y’ || again == ‘Y’ ) .

4.) The while-loop on line 5 has no body. The semi-colon (‘;’) immediately following the parentheses on line 5 is the cause of this. You will have to remove the semi-colon and add some braces (‘<‘ and ‘>‘) around all of the code that should be part of the while-loop’s body.

That should be a good start. I’ve appended this basic code as a guide:

Xismn,
Thank you
I followed all of your directions, I no longer have any errors in my code but when I run it the black boxes opens and nothing is in it. It should be asking for a Fahrenheit degree and then give it to me Celsius, and then ask if I want to convert more values. I don’t know where to go from here, with no errors showing up
This is what have now

Источник

See more:

What have i done wrong. i have been puzzled for 2 hours now.

#include "placeName.h"
#include <iostream>
#include <string>
using namespace std;
placeName::placeName()
class RandonRegionName{
    public:
{
    int P_Name(){
    srand(static_cast<unsigned int>(time(0)));
    int placeName = rand();

    return (placeName % 3) + 1;
}

    void randomPlaceName(){
        string RegionName;
       if (placeName == 1){
        RegionName = "Pandonia";

       }else if (placeName == 2){
         RegionName = "Shires";
       }else if (placeName == 3){
          RegionName = "Epic";
       }

    }}
};


1 solution

Solution 1

The wrong fragment is the line placeName::placeName(), some kind of incomplete fragment of code. Remove it. It cannot even guess what could be your idea behind that.

On the top-level of C++ text, you can only have any kinds of declarations/definitions, not anything else like operators, statements (functions calls), etc.

—SA

Comments

+5, lots of times cryptic errors mean nothing else but something above it is out of order. Key words to look for in that case are «Expected» «unknown token», etc.

Thank you, Ron.
I would say, C++ compilation errors are way, way more cryptic compared to Borland Pascal and the followers, including .NET languages.
—SA

Indeed, can’t say how many hours I’ve spent debugging a missing ; and getting a lot of very strange errors. I can really appreciate .NET’s on the fly compilation and code highlighting, probably one of the most underestimated features of modern IDE’s.

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Development & Programming
  • Programming Talk
  • [SOLVED] C++: expected initializer before �class�

  1. [SOLVED] C++: expected initializer before �class�

    Hello,

    I cannot for the life of me, figure out WHAT the error is! I’ve checked the code over and over for errors, and cannot find any. If I remove the class from the file it says the error is coming from (parseargs.h), it pops up another error…
    With class:

    Code:

    /home/user/Projects/rsuploader/src/parseargs.h:21: error: expected initializer before �class�

    With class removed:

    Code:

    In file included from /usr/include/c++/4.4/bits/ios_base.h:43,
                     from /usr/include/c++/4.4/ios:43,
                     from /usr/include/c++/4.4/ostream:40,
                     from /usr/include/c++/4.4/iostream:40,
                     from /home/user/Projects/rsuploader/src/main.cpp:29:

    And here’s a zip of my project…

    Last edited by James78; June 1st, 2010 at 12:00 AM.

    Reason: Made it easier to read..


  2. Re: C++: expected initializer before �class�

    In functions.h, the printError declaration is missing a semi-colon.


  3. Re: C++: expected initializer before �class�

    It would be wouldn’t it. Thanks. How we even miss such simple things… >.<


Bookmarks

Bookmarks


Posting Permissions

BalexD

0 / 0 / 0

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

Сообщений: 16

1

28.12.2013, 21:41. Показов 30160. Ответов 11

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


В общем, компилятор почему-то ругается на 3 строку, говоря «expected initializer before void» Что ему тут не нравится — ума не приложу. Все функции есть в хидере, ругаться стал недавно — ранее работал на ура. Перестраивала, перезапускала блокс(на всяк пожарный), а толку нет. Вот сам код:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "HW_C.h"
 
void less_1()
{
    bool flag=true;
    int temp;
    system("clear");
    while(flag)
    {
        printf("nВыберите задание:nt1 Среднее арифметическое двух чиселnt2 Перевод гривны в валютуnt3 Вывод текстаnt4 Квадрат числаnt5 Сумма и произведение трёхnt6 Назадn");
        scanf("%d", &temp);
        system("clear");
        switch(temp)
        {
            case 1: printf("Среднее арифметическое: %.3lfn",arithmetic_average()); break;
            case 2: exchange();break;
            case 3: text();break;
            case 4: printf("%dn", sqr()); break;
            case 5: summ_and_product_of_3();break;
            case 6: flag=false; break;
        }
    }
}

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



0



Модератор

Эксперт С++

12641 / 10135 / 6102

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

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

28.12.2013, 21:48

2

Что-то не так в HW_C.h
Что там написано?



0



Эксперт С++

1672 / 1044 / 174

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

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

28.12.2013, 21:48

3

Логично предположить, что ошибка в файле HW_C.h. Например, отсутствие точки с запятой после определения структуры.



0



17 / 17 / 2

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

Сообщений: 114

28.12.2013, 21:50

4

Что-то в заголовочном файле не так. Покажите нам его, пожалуйста.



0



BalexD

0 / 0 / 0

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

Сообщений: 16

28.12.2013, 22:07

 [ТС]

5

Вот та самая часть хидера:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <iomanip>
 
using namespace std;
 
 
void less_1();
void exchange();
void text();
int sqr();
void summ_and_product_of_3();
double arithmetic_average();
 
void less_2();
bool even_or_odd();
void summ_and_amount();



0



Модератор

Эксперт С++

12641 / 10135 / 6102

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

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

29.12.2013, 11:03

6

У меня это все компилируется.
Возможно перепутали несколько одинаковых HW_C.h
В строчке
#include «HW_C.h»
щелкните правой кнопкой мыши по HW_C.h и выберите
Open HW_C.h (Открытие документа HW_C.h).



0



0 / 0 / 0

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

Сообщений: 16

03.01.2014, 02:07

 [ТС]

7

Проблема в том, что HW_C.h — один-единственный. И других просто нету. Уж не знаю, на что грешить(



0



5493 / 4888 / 831

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

Сообщений: 13,587

03.01.2014, 02:14

8

Весь проект выкладывайте.



0



0 / 0 / 0

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

Сообщений: 16

08.01.2014, 20:02

 [ТС]

9

Ну, кидаю в виде ссылки. Чтоб никто не терялся: сама функция используется в HW_Dop1.cpp, а в хидере прописана в самом конце.



0



5493 / 4888 / 831

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

Сообщений: 13,587

09.01.2014, 04:58

10

Вот результат компиляции этого проекта в Code::Blocks 12.11:

objDebugHW_Dop1.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugHW_Dop2.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugHW_Dop3.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugHW_Dop4.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_1.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_2.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_3.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_4.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_5.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_6.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugmain.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
||=== Build finished: 22 errors, 0 warnings (0 minutes, 4 seconds) ===|

И при чём здесь тогда:

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

компилятор почему-то ругается на 3 строку, говоря «expected initializer before void»

???

Добавлено через 1 минуту
И кто вас научил делать реализацию функции (insert_4_numb()) в заголовочном файле?

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

сама функция используется в HW_Dop1.cpp, а в хидере прописана в самом конце.



1



0 / 0 / 0

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

Сообщений: 16

10.01.2014, 00:02

 [ТС]

11

Хм.. Странно. У меня все выглядит немного по-другому.

А про заголовочный файл скажу, что никто мне не говорил, что так делать нельзя. По крайней мере, до этого момента ошибки не возникало. Что же, учтем и эти грабли.

Но спасибо за указания на промахи. Искренне всем благодарна)



0



5493 / 4888 / 831

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

Сообщений: 13,587

10.01.2014, 00:07

12

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

Хм.. Странно. У меня все выглядит немного по-другому.

Интересно было бы посмотреть.



0



  • Forum
  • Beginners
  • Expected initializer before ‘.’ token

Expected initializer before ‘.’ token

I’m writing a class with an array and I’m supposed to calculate the average of some entered grades outside the class and in the main but I get the error
Expected Initializer before ‘.’ token

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
 #include <iostream>

using std::cout;
using std::cin;
using std::endl;

class Student{
    private:
    float grades[10];

    public:
    void setGrades()
    {
        float grades[10];
        int i;
        for(i = 0; i < 10; i++)
        {
            cout << "Enter Grade # " << i + 1 << endl;
            cin >> grades[i];
            cout << endl;
        }
    }

    float getGrade ()
    {
        int i;

        cout << "Grades" << endl;;

        for(i = 0; i < 10; i++)
        {
            cout << "  " << grades[i] << endl;
        }
    }

};

int main () {
    Student gradeAverage;
    float grades = 0.0;

    gradeAverage.setGrades();

    float gradeAverage.getGrade();
    float computeAverage = 0;

    for(int i = 0; i < 5; i++)
    {
        computeAverage = computeAverage + gradeAverage.getGrade();
    }

    cout << computeAverage/5 << endl;

    return 0;
}

I’m not to sure what to do or i even did the class right
Please help!

A compiler says more than just: «error». It also mentions line of code.
For example:

 In member function 'float Student::getGrade()':
34:5: warning: no return statement in function returning non-void [-Wreturn-type]

 In function 'int main()':
44:23: error: expected initializer before '.' token
40:11: warning: unused variable 'grades' [-Wunused-variable]

Two warnings.

What if I promised you $1000, but then just walk away, leaving you empty handed?
You make a promise on line 24, but you don’t keep it.

The error is on line 44. Please explain this code:
float gradeAverage.getGrade();

Yeah sorry i forgot to put where i had the error.
I understand what you mean by that analogy but I don’t understand what’s a fix for it in the code.
And this was a mistake i didn’t mean to type that
float gradeAverage.getGrade();

If the problem is

, what do you think the solution might be?

Hello Brandon17,

Line 44 looks like a nice prototype, but what is it doing in the middle of the program?

In the function «getGrade()» Why are you printing the array when you should be returning something from the array. In this case the «getGrade()» function should have a parameter the represents the element of the array that you need.

As you have it «float getGrade ()» would be better named «void printGrades ()».

Hope that helps,

Andy

I know that i shouldn’t be printing the there but the question was my teacher gave me was this
Write a class called Student that contains a property called grades that can store a
maximum of 10 grades. Create a setter and a getter method. The setter method
will take no parameters and return no parameters. Instead, within the setter
method you must construct a loop that will ask the user to enter 10 grades. The
getter method will simply print the 10 grades; so, it will take no and return no
parameters. Yes, that is a misnomer; this is because passing and returning arrays
has not been covered yet. Create another method called computeAverage that
return the average of all the grades. Create another method called
minimumGrade that returns the minimum grade the student received.

He knows it’s a misnomer but he wants us to do it anyway.
He hasn’t covered it yet so I was just looking it up but nothing I find helps

Hello Brandon17,

Now that I see what is required I will take a look tomorrow and see what I can do.

Andy

The following cannot be compiled.
float gradeAverage.getGrade();

To resolve compilation error, change to
grades=gradeAverage.getGrade();
or simply remove «float» as follows
gradeAverage.getGrade();

Last edited on

you have some issues to resolve here,

i think you should rename setGrades() and getGrades() to inputGrades() and outputGrades() so the names match the functionality better, you are calling getGrade() expecting to get a grade but thats not what the function does, and it does not return a grade at all, its name has misled you. If your tutor did not tell you what to call the functions then rename them to be more meaningful and because it does not return a value it should be «void».

you have not added a function computeAverage() that your tutor asked for. Let it calculate the average from the grades array and return it. because it will return a float value, it should be declared as float computeAverage().

1
2
3
4
    Student student;
    student.setGrades();  // assign the grades
    student.getGrades();  // list the grades
    cout << student.computeAverage() << endl;  // output the average 

Last edited on

Hello Brandon17,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Write a class called Student that contains a property called grades that can store a maximum of 10 grades.

Create a setter and a getter method.

The setter method will take no parameters and return no parameters. Instead, within the setter method you must construct
a loop that will ask the user to enter 10 grades.

The getter method will simply print the 10 grades; so, it will take no and return no parameters.

Yes, that is a misnomer; this is because passing and returning arrays has not been covered yet.

Create another method called computeAverage that return the average of all the grades.

Create another method called minimumGrade that returns the minimum grade the student received.

He knows it's a misnomer but he wants us to do it anyway. 

In lines 5 and 8 it says will take no parameters and return no parameters yet the get function is trying to return a float, but it should return nothing.

Now you need to create two functions «computeAverage» and » minimumGrade» and both do return a value.

Give it a try and see what you can come up with. We can always fix what is wrong.

Hope that helps,

Andy

Hello Brandon17,

I reworked the «set» function to speed up testing. I looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void setGrades()  // <--- Should be renamed.
{
	double gradesArr[MAXSIZE]{ 85, 89, 77, 100, 95, 91, 87, 97, 93, 87 };  // <--- Added for testing. Comment out when finished.
	int i;

	for (i = 0; i < MAXSIZE; i++)
	{
		//cout << "Enter Grade # " << i + 1 << ": ";  // <--- Changed. Removed the "endl". Puts input on same line as prompt.
		//cin >> grades[i];
		grades[i] = gradesArr[i];  // <--- Added for testing.
		//cout << endl;  // <--- Commented for testing.
	}

	std::cout << std::endl;  // <--- Used for testing.
}

This way the array in the class is loaded with the same numbers each time the program is run. It helps in seeing how other functions work because you are using the same numbers each time and you do not have to enter ten numbers each time the program runs. Once working you can change back to getting the user input.

Just a little trick to cut down on testing time.

Hope that helps,

Andy

Topic archived. No new replies allowed.

Одна из самых неприятных ошибок — это ошибка компиляции для платы Аrduino Nano, с которой вам придется столкнуться не раз.

Содержание

  • Синтаксические ошибки
  • Ошибки компиляции плат Arduino uno
  • Ошибка exit status 1 при компиляции для плат uno, mega и nano
  • Ошибки библиотек
  • Ошибки компилятора Ардуино
  • Основные ошибки
    • Ошибка: «avrdude: stk500_recv(): programmer is not responding»
    • Ошибка: «a function-definition is not allowed here before ‘{‘ token»
    • Ошибка: «No such file or directory  /  exit status 1»
    • Ошибка: «expected initializer before ‘}’ token  /  expected ‘;’ before ‘}’ token»
    • Ошибка: «… was not declared in this scope»

Синтаксические ошибки

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

Сразу же при покупке они получают готовый набор библиотек на С99 и возможность, по необходимости, подтянуть необходимые модули в опен-соурс источниках.

Но и здесь не избежать множества проблем, с которыми знаком каждый программист, и одна из самых неприятных – ошибка компиляции для платы Аrduino nano, с которой вам придется столкнуться не раз. Что же эта строчка означает, какие у неё причины появления, и главное – как быстро решить данную проблему?

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

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

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

Мы узнали, к чему приводит данный процесс, давайте разберёмся, как он происходит:

  1. Первое, что делает компилятор – подгружает все инклуднутые файлы, а также меняет объявленные дефайны на значения, которое для них указано. Это необходимо затем, чтобы не нужно было по нескольку раз проходиться синтаксическим парсером в пределах одного кода. Также, в зависимости от среды, компилятор может подставлять функции на место их объявления или делать это уже после прохода синтаксическим парсером. В случае с С99, используется второй вариант реализации, но это и не столь важно.
  2. Далее он проверяет первичный синтаксис. Этот процесс проводится в изначальном компилируемом файле, и своеобразный парсер ищет, были ли описаны приведенные функции ранее, подключены ли необходимые библиотеки и прочее. Также проверяется правильность приведения типов данных к определенным значениям. Не стоит забывать, что в С99 используется строгая явная типизация, и вы не можете засунуть в строку, объявленную integer, какие-то буквенные значения. Если такое замечается, сразу вылетает ошибка.
  3. В зависимости от среды разработки, иногда предоставляется возможность последний раз протестировать код, который сейчас будет компилироваться, с запуском интерпретатора соответственно.
  4. Последним идет стек из различных действий приведения функций, базовых операнд и прочего к двоичному коду, что может занять какое-то время. Также вся структура файлов переносится в исполняемые exe-шники, а затем происходит завершение компиляции.

Как можно увидеть, процесс не так прост, как его рисуют, и на любом этапе может возникнуть какая-то ошибка, которая приведет к остановке компиляции. Проблема в том, что, в отличие от первых трех этапов, баги на последнем – зачастую неявные, но всё ещё не связанные с алгоритмом и логикой программы. Соответственно, их исправление и зачистка занимают значительно больше времени.

А вот синтаксические ошибки – самая частая причина, почему на exit status 1 происходит ошибка компиляции для платы Аrduino nano. Зачастую процесс дебагинга в этом случае предельно простой.

Вам высвечивают ошибку и строчку, а также подсказку от оператора EXCEPTION, что конкретно не понравилось парсеру. Будь то запятая или не закрытые скобки функции, проблема загрузки в плату Аrduino возникнет в любом случае.

Решение предельно простое и логичное – найти и исправить непонравившийся машине синтаксис. Зачастую такие сообщения вылезают пачками, как на этапе тестирования, так и компилирования, поэтому вы можете таким образом «застопорить» разработку не один раз.

Не стоит этого страшиться – этот процесс вполне нормален. Все претензии выводятся на английском, например, часто можно увидеть такое: was not declared in this scope. Что это за ошибка arduino – на самом деле ответ уже скрыт в сообщении. Функция или переменная просто не были задекларированы в области видимости.

Ошибки компиляции плат Arduino uno

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

Соответственно, если в меню среды вы выбрали компиляцию не под тот МК, то вполне вероятно, что вызываемая вами функция или метод просто не будет найдена в постоянной памяти, вернув ошибку. Стандартно, в настройках указана плата Ардуино уно, поэтому не забывайте её менять. И обратная ситуация может стать причиной, по которой возникает проблема загрузки в плату на Аrduino uno.

Ошибка exit status 1 при компиляции для плат uno, mega и nano

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

В документации указано, что это сообщение указывает на то, что не запускается ide Аrduino в нужной конфигурации, но на деле есть ещё десяток случаев, при которых вы увидите данное сообщение. Однако, действительно, не забывайте проверять разрядность системы, IDE и просматривать, какие библиотеки вам доступны для обращения на текущий момент.

Ошибки библиотек

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

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

Ошибки компилятора Ардуино

Ранее упоминался финальный стек действий, при прогонке кода через компилятор, и в этот момент могут произойти наиболее страшные ошибки – баги самого IDE. Здесь конкретного решения быть не может. Вам никто не запрещает залезть в ядро системы и проверить там всё самостоятельно, но куда эффективнее будет откатиться до предыдущей версии программы или, наоборот, обновиться.

Основные ошибки

Ошибка: «avrdude: stk500_recv(): programmer is not responding»

Смотрим какая у нас плата? Какой порт используем? Сообщаем ардуино о правильной плате и порте. Возможно, что используете Nano, а указана Mega. Возможно, что указали неверный порт. Всё это приводит к сообщению: «programmer is not responding».

Решение:

В Arduino IDE в меню «Сервис» выбираем плату. В меню «Сервис → Последовательный порт» выбираем порт.

Ошибка: «a function-definition is not allowed here before ‘{‘ token»

Забыли в коде программы (скетча) закрыть фигурную скобку }.

Решение:

Обычно в Ардуино IDE строка с ошибкой подсвечивается.

Ошибка: «No such file or directory  /  exit status 1»

Подключаемая библиотека отсутствует в папке libraries.

Решение:

Скачать нужную библиотеку и скопировать её в папку программы — как пример — C:Program FilesArduinolibraries. В случае наличия библиотеки — заменить файлы в папке.

Ошибка: «expected initializer before ‘}’ token  /  expected ‘;’ before ‘}’ token»

Забыли открыть фигурную скобку {, если видим «initializer before». Ошибка «expected ‘;’ before ‘}’ token» — забыли поставить точку с запятой в конце командной строки.

Решение:

Обычно в Ардуино IDE строка с ошибкой подсвечивается.

Ошибка: «… was not declared in this scope»

Arduino IDE видит в коде выражения или символы, которые не являются служебными или не были объявлены переменными.

Решение:

Проверить код на использование неизвестных выражений или лишних символов.

17 июля 2018 в 13:23
| Обновлено 7 ноября 2020 в 01:20 (редакция)
Опубликовано:

Статьи, Arduino

  1. Я пишу пустой код, безо всего, выделяет слово void и выдаёт такую ошибку:

    Arduino: 1.6.8 (Windows 7), Плата:»Arduino/Genuino Uno»

    sketch_may03a:7: error: expected initializer before ‘void’

    E:СашаАрдуйноsketch_may03asketch_may03a.ino: In function ‘void setup()’:

    sketch_may03a:5: error: expected ‘;’ before ‘}’ token

    E:СашаАрдуйноsketch_may03asketch_may03a.ino: In function ‘void loop()’:

    sketch_may03a:10: error: expected ‘;’ before ‘}’ token

    exit status 1
    expected initializer before ‘void’

    Что делать? Скачал программу с официального сайта.

  2. внимательно читать сообщение об ошибке: в функции setup() в строках 5 и 10 отсутствует символ «;» в конце строки.

  3. кто может помочь в этом??

    Вложения:

    • 2016-05-03 (1).png

  4. Не определен объект Audio. Скорее всего отсутствует библиотека или она не включена в программу.

  5. Arduino: 1.6.8 Hourly Build 2016/01/27 03:44 (Windows 10), Плата:»Arduino/Genuino Uno»

    sketch_oct31a:53: error: expected unqualified-id before ‘{‘ token

    sketch_oct31a:61: error: expected declaration before ‘}’ token

    exit status 1
    expected unqualified-id before ‘{‘ token

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

    Помогите! Обьясните что делать?

  6. C:UsersUserDesktoparduino-nightlyhardwarearduinoavrcoresarduino/main.cpp:43: undefined reference to `setup’

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Ошибка компиляции для платы Arduino/Genuino Uno.
    Что за ошибка?

Понравилась статья? Поделить с друзьями:
  • Error expected initializer before cin
  • Error expected initializer before char
  • Error expected indentation of 6 spaces but found 4 indent
  • Error expected identifier or before while
  • Error expected identifier or before token