Меню

Expected constructor destructor or type conversion before token ошибка

Compiling polygone.h and polygone.cc gives error:

polygone.cc:5:19: error: expected constructor, destructor, or type conversion before ‘(’ token

Code:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

# include <iostream>

class Polygone {

    public:
        Polygone(){};
        Polygone(std::string fichier);

};

# endif

and

//polygone.cc
# include <iostream>
# include <fstream>
# include "polygone.h"

Polygone::Polygone(string nom)
{
    std::ifstream fichier (nom, ios::in);
    std::string line;

    if (fichier.is_open())
    {
        while ( fichier.good() )
        {
            getline (fichier, line);
            std::cout << line << std::endl;
        }
    }
    else
    {
        std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
    }
}

//ifstream fich1 (argv[1], ios::in);

My guess is that the compiler is not recognising Polygone::Polygone(string nom) as a constructor, but, if this actually is the case, I have no idea why.

Any help?

asked Jan 22, 2012 at 0:42

Marconius's user avatar

2

This is not only a ‘newbie’ scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.

The bottom line seems to be this: If the compiler can’t match the definition’s signature to the declaration’s signature it thinks the definition is not a constructor and then doesn’t know how to parse the code and displays this error. Which is also what happened for the OP: std::string is not the same type as string so the declaration’s signature differed from the definition’s and this message was spit out.

As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn’t match rather than giving this message.

answered Jan 25, 2019 at 22:16

Bob Kocisko's user avatar

Bob KociskoBob Kocisko

5441 gold badge7 silver badges14 bronze badges

The first constructor in the header should not end with a semicolon. #include <string> is missing in the header. string is not qualified with std:: in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream is broken. I suggest learning C++ before trying to use it.

Let’s fix this up:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>    

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

and

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>


Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);


  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

Sandeep Datta's user avatar

answered Jan 22, 2012 at 0:47

pmr's user avatar

pmrpmr

57.7k10 gold badges110 silver badges155 bronze badges

5

You are missing the std namespace reference in the cc file. You should also call nom.c_str() because there is no implicit conversion from std::string to const char * expected by ifstream‘s constructor.

Polygone::Polygone(std::string nom) {
    std::ifstream fichier (nom.c_str(), std::ifstream::in);
    // ...
}

answered Jan 22, 2012 at 0:50

Sergey Kalinichenko's user avatar

You need the return type, for example «void Polygon…»

answered Nov 10, 2021 at 16:32

maddy's user avatar

2

I’m trying to compile my code to test a function to read and print a data file, but I get a compiling error that I don’t understand — «error: expected constructor, destructor, or type conversion before ‘;’ token». Wall of relevant code-text is below.

struct Day
{
  int DayNum;
  int TempMax;
  int TempMin;
  double Precip;
  int TempRange;
};

struct Month
{
  Day Days[31];
  int MonthMaxTemp;
  int MonthMinTemp;
  double TotalPrecip;
  int MonthMaxTempRange;
  int MonthMinTempRange;
  double AverageMaxTemp;
  double AverageMinTemp;
  int RainyDays;
  double AveragePrecip;
}theMonth;

double GetMonth();

double GetMonth()
{
  for (int Today = 1; Today < 31; Today++)
    {
      cout << theMonth.Days[Today].TempMax << theMonth.Days[Today].TempMin;
      cout << theMonth.Days[Today].Precip;
    }
  return 0;
}

GetMonth();  // compile error reported here

asked Oct 15, 2009 at 15:36

Owen Pierce's user avatar

1

The line with the error looks like you’re trying to call GetMonth — but at the global level, a C++ program consists of a series of declarations. Since a function call isn’t a declaration, it can’t exist in isolation at the global level. You can have a declaration that’s also a definition, in which case it can invoke a function as part of initialization.

A function call by itself, however, has to be contained within some other function:

#ifdef TEST
int main() { 
    GetMonth();
}
#endif

answered Oct 15, 2009 at 15:41

Jerry Coffin's user avatar

Jerry CoffinJerry Coffin

467k79 gold badges617 silver badges1097 bronze badges

1

(In addition to other replies.) In order to excute your ‘GetMonth()’ function you have to either call it from another function (‘main’ or whatever is called from ‘main’) or use it in initializer expression of an object declared at namespace scope, as in

double global_dummy = GetMonth();

However, the latter method might suffer from initialization order problems, which is why it is recommended to use the former method whenever possible.

answered Oct 15, 2009 at 16:03

AnT stands with Russia's user avatar

0

In C/C++, you cannot simply add executable code into the body of a header or implementation (.c,.cpp,.cxx,etc…) file. Instead you must add it to a function. If you want to have the code run on startup, make sure to add it to the main method.

int main(int argc, char *argv[]) {
  GetMonth();
}

answered Oct 15, 2009 at 15:41

JaredPar's user avatar

JaredParJaredPar

721k147 gold badges1226 silver badges1447 bronze badges

C++ programs don’t execute in a global context. This means you need to put the call to GetMonth into a function for it to run. int main() { } might be appropriate.

answered Oct 15, 2009 at 15:43

Andres Jaan Tack's user avatar

Andres Jaan TackAndres Jaan Tack

22.3k10 gold badges59 silver badges77 bronze badges

Offline

Зарегистрирован: 05.12.2015

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

long duration,cm;

void setup()
{
  pinMode (10,OUTPUT);//на реле
pinMode (11, OUTPUT);// триг
pinMode (12, INPUT); //эхо


Serial.begin (9600);
}

void loop() {
duration = pulseIn (12,HIGH);
cm = duration/29/2;

if (cm<20){ digitalWrite(10, HIGH); } //если менее 10см - выключаем


else if (cm<=150) // Если расстояние менее 150 сантиметров 

{ 
   digitalWrite(10, LOW); // Включаем светодиод 
   
  
   delay(500000); //задержка на выключение 
}  
else 
{ 
   digitalWrite(10, HIGH); // иначе выключаем
} 
  }
  
else
{
digitalWrite(10, HIGH);  // включаем LOW
}
Serial.print(cm);
Serial.print("CM");
Serial.println ();
  
delay(100); // делает замер каждые  -- сек

}

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

Arduino: 1.6.0 (Windows 8), Плата»Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)»

HC-SR04.ino:44:1: error: stray » in program

HC-SR04.ino:34:1: error: expected unqualified-id before ‘else’

HC-SR04.ino:38:1: error: ‘Serial’ does not name a type

HC-SR04.ino:39:1: error: ‘Serial’ does not name a type

HC-SR04.ino:40:1: error: ‘Serial’ does not name a type

HC-SR04.ino:42:6: error: expected constructor, destructor, or type conversion before ‘(‘ token

HC-SR04.ino:44:1: error: expected declaration before ‘}’ token

Ошибка компиляции.

  This report would have more information with

  «Отображать вывод во время компиляции»

  enabled in File > Preferences.

Подскажите пожалуйста что здесь не так. В програмировании я новичёк:)

Не судите строго.

I am new in here, posting because I have read several posts that have help me.I know you may regard this post as another duplicate, while it’s not. It’s not a duplicate because my code is different than others. Here is my code as:

#include "bcm2835.h"
#include <cmath>
#include <iostream>
using namespace std;


// COMMANDS
#define WAKEUP 0x02
#define SLEEP  0x04
#define RESET  0x06
#define START  0x09
#define STOP   0x0a
#define RDATAC 0x10
#define SDATAC 0x11
#define RDATA  0x12
#define OFSCAL 0x18
#define GANCAL 0x19
#define RREG1  0x20
#define WREG1  0x40
#define RREG2  0x08
#define WREG2  0x08

// REGISTERS
#define CONFIG0 0x85
#define CONFIG1 0x10       // checksum is kept off
#define CONFIG2 0x15       //10SPS data rate and Gate control mode
#define OFC0    0x00
#define OFC1    0x00
#define OFC2    0x00
#define FSC0    0x00
#define FSC1    0x00
#define FSC2    0x40
#define NUM     1024

int nobytes;
int S = 50;
int i,flag = 1;
int j, k, factor, converged, count = 0;
char status = LOW;
char txbuffer[11], rxbuffer[4], dummy;
float xhat, xhat_m, P_m, L , K, last_xhat_converged, xhat_converged = 0.0;
float P = 1.0;
float R = 0.01;
float Q, mean, variance = 0;
float current, lastreading, current_test[50];
double key, startkey;
float X1[4096];
float X2[4096];
float Xf1[4096];
float Xf2[4096];
float v[4096];
float xf[4096];
float c[65536];
float ys[65536];

spi_start();
initialise();


void spi_start()
 {
bcm2835_init();
//cout << "The SPI mode is starting";
// INITIAL SETUP OF THE SPI DEVICE
bcm2835_spi_begin();                                          // Setup the SPI0 port on the RaspberryPi
bcm2835_spi_chipSelect(BCM2835_SPI_CS0);                      // Assert the chip select
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);      // Set the Bit order
bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);      // Set the the chip select to be active low
bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_64);    // Set the clock divider, SPI speed is 3.90625MHz
bcm2835_spi_setDataMode(BCM2835_SPI_MODE1);                   // Set the Data mode
//cout << "The SPI mode has been started";
 }

void initialise()
 {
// INITIAL RESET OF THE CHIP
nobytes = 1;
txbuffer[0] = RESET;
bcm2835_spi_writenb(txbuffer, nobytes);
bcm2835_delay(100); //no accurate timing required

// WRITING OF THE CONTROL AND THE CALIBRATION REGISTERS
nobytes = 11;
txbuffer[0] = WREG1;
txbuffer[1] = WREG2;
txbuffer[2] = CONFIG0;
txbuffer[3] = CONFIG1;
txbuffer[4] = CONFIG2;
txbuffer[5] = OFC0;
txbuffer[6] = OFC1;
txbuffer[7] = OFC2;
txbuffer[8] = FSC0;
txbuffer[9] = FSC1;
txbuffer[10]= FSC2;
bcm2835_spi_writenb(txbuffer, nobytes);
bcm2835_delay(100); //no accurate timing required

 }

suggestions will be appreciated.

I am new in here, posting because I have read several posts that have help me.I know you may regard this post as another duplicate, while it’s not. It’s not a duplicate because my code is different than others. Here is my code as:

#include "bcm2835.h"
#include <cmath>
#include <iostream>
using namespace std;


// COMMANDS
#define WAKEUP 0x02
#define SLEEP  0x04
#define RESET  0x06
#define START  0x09
#define STOP   0x0a
#define RDATAC 0x10
#define SDATAC 0x11
#define RDATA  0x12
#define OFSCAL 0x18
#define GANCAL 0x19
#define RREG1  0x20
#define WREG1  0x40
#define RREG2  0x08
#define WREG2  0x08

// REGISTERS
#define CONFIG0 0x85
#define CONFIG1 0x10       // checksum is kept off
#define CONFIG2 0x15       //10SPS data rate and Gate control mode
#define OFC0    0x00
#define OFC1    0x00
#define OFC2    0x00
#define FSC0    0x00
#define FSC1    0x00
#define FSC2    0x40
#define NUM     1024

int nobytes;
int S = 50;
int i,flag = 1;
int j, k, factor, converged, count = 0;
char status = LOW;
char txbuffer[11], rxbuffer[4], dummy;
float xhat, xhat_m, P_m, L , K, last_xhat_converged, xhat_converged = 0.0;
float P = 1.0;
float R = 0.01;
float Q, mean, variance = 0;
float current, lastreading, current_test[50];
double key, startkey;
float X1[4096];
float X2[4096];
float Xf1[4096];
float Xf2[4096];
float v[4096];
float xf[4096];
float c[65536];
float ys[65536];

spi_start();
initialise();


void spi_start()
 {
bcm2835_init();
//cout << "The SPI mode is starting";
// INITIAL SETUP OF THE SPI DEVICE
bcm2835_spi_begin();                                          // Setup the SPI0 port on the RaspberryPi
bcm2835_spi_chipSelect(BCM2835_SPI_CS0);                      // Assert the chip select
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);      // Set the Bit order
bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);      // Set the the chip select to be active low
bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_64);    // Set the clock divider, SPI speed is 3.90625MHz
bcm2835_spi_setDataMode(BCM2835_SPI_MODE1);                   // Set the Data mode
//cout << "The SPI mode has been started";
 }

void initialise()
 {
// INITIAL RESET OF THE CHIP
nobytes = 1;
txbuffer[0] = RESET;
bcm2835_spi_writenb(txbuffer, nobytes);
bcm2835_delay(100); //no accurate timing required

// WRITING OF THE CONTROL AND THE CALIBRATION REGISTERS
nobytes = 11;
txbuffer[0] = WREG1;
txbuffer[1] = WREG2;
txbuffer[2] = CONFIG0;
txbuffer[3] = CONFIG1;
txbuffer[4] = CONFIG2;
txbuffer[5] = OFC0;
txbuffer[6] = OFC1;
txbuffer[7] = OFC2;
txbuffer[8] = FSC0;
txbuffer[9] = FSC1;
txbuffer[10]= FSC2;
bcm2835_spi_writenb(txbuffer, nobytes);
bcm2835_delay(100); //no accurate timing required

 }

suggestions will be appreciated.

Hunter13ua

46 / 46 / 18

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

Сообщений: 183

1

29.10.2013, 15:02. Показов 5501. Ответов 26

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


C++
1
2
3
4
5
6
7
8
9
10
struct Gf3 {
    GLfloat x;
    GLfloat y;
    GLfloat z;
} p1,p2,p3,t;
 
t.x = 0.0; t.y = 0.0; t.z = 1.0;
p1.x = 0.0; p1.y = 0.942809; p1.z = -0.333333;
p2.x = -0.816497; p2.y = -0.471405; p2.z = -0.333333;
p3.x = 0.816497; p3.y = -0.471405; p3.z = -0.333333;

Ошибки на строчках с присваиванием.

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

29.10.2013, 15:02

Ответы с готовыми решениями:

Ошибка expected constructor, destructor, or type conversion before ‘;’ token
выдает ошибку expected constructor, destructor, or type conversion before ‘;’ token с 61-90…

Ошибка error: ./SDK/SDK.h:11:37: error: expected constructor, destructor, or type conversion before ‘(‘ token
Возникает такая ошибка при компиляции, в коде особо не разбираюсь, прошу помочь, вот код:

Ошибка expected constructor, destructor, or type conversion before ‘(‘ toke
Возникает ошибка expected constructor, destructor, or type conversion before ‘(‘ toke в 7 и 16…

Ошибка «expected constructor, destructor, or type conversion»
//ourfunc.cpp — îïðåäåëÿåò âàøó ñîáñòâåííóþ ôóíêöèþ
#include &lt;iostream&gt;
using namespace std;…

26

2061 / 617 / 41

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

Сообщений: 4,468

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

29.10.2013, 15:26

2

В приведенном коде нет никаких ошибок.



0



Hunter13ua

46 / 46 / 18

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

Сообщений: 183

29.10.2013, 15:29

 [ТС]

3

Могу предоставить весь код ..

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
#include <windows.h>
#include <GL/glut.h>
 
#include <stdlib.h>
#include <iostream>
using namespace std;
 
struct Gf3 {
    GLfloat x;
    GLfloat y;
    GLfloat z;
} p1,p2,p3,t;
 
t.x = 0.0; t.y = 0.0; t.z = 1.0;
p1.x = 0.0; p1.y = 0.942809; p1.z = -0.333333;
p2.x = -0.816497; p2.y = -0.471405; p2.z = -0.333333;
p3.x = 0.816497; p3.y = -0.471405; p3.z = -0.333333;
 
void myInit(void);
void display(void);
void reshape(int,int);
 
int main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_DEPTH );
    glutInitWindowSize(640, 640);
    glutInitWindowPosition(300, 0);
    glutCreateWindow("Aproximization sphere");
 
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
 
    myInit();
    glutMainLoop();
 
    return EXIT_SUCCESS;
}
 
void myInit(void) {
    glOrtho(-2.0, 2.0, -2.0, 2.0, -10.0, 10.0);
    glDepthFunc(GL_LESS);
}
 
void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glClear(GL_DEPTH_BUFFER_BIT);
 
    glutSwapBuffers();
}
 
void reshape(int width, int height){
    glViewport(0,0,width,height);
    glutPostRedisplay();
}

Код

Desktopgraphics4spheremain.cpp|14|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|14|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|14|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|15|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|15|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|15|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|16|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|16|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|16|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|17|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|17|error: expected constructor, destructor, or type conversion before '.' token|
Desktopgraphics4spheremain.cpp|17|error: expected constructor, destructor, or type conversion before '.' token|
||=== Build finished: 12 errors, 0 warnings ===|



0



243 / 244 / 38

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

Сообщений: 927

29.10.2013, 15:31

4

Hunter13ua, попробуйте запихнуть эти строки в main()



1



2061 / 617 / 41

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

Сообщений: 4,468

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

29.10.2013, 15:35

5

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

Hunter13ua, попробуйте запихнуть эти строки в main()

А так как это глут, то в спец. функцию инициализации.



0



46 / 46 / 18

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

Сообщений: 183

29.10.2013, 15:35

 [ТС]

6

metaluga145, .. Если понимаете, что за хрень, поясните, пожалуйста.
Почему работает внутри main, и не компилит вне ?



0



2061 / 617 / 41

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

Сообщений: 4,468

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

29.10.2013, 15:38

7

например в myInit();

Добавлено через 1 минуту
Hunter13ua, потому что по стандарту положено.



1



243 / 244 / 38

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

Сообщений: 927

29.10.2013, 15:39

8

Не по теме:

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

так как это глут, то в спец. функцию инициализации.

что-что? поясните)

Hunter13ua, не понимаю, но судя по комментарию выше про «функцию инициализиции», сейчас пойму



0



Форумчанин

Эксперт CЭксперт С++

8193 / 5043 / 1437

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

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

29.10.2013, 15:39

9

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

Почему работает внутри main, и не компилит вне ?

Порядок создания глобальных переменных неопределен



0



243 / 244 / 38

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

Сообщений: 927

29.10.2013, 15:39

10

programina, это специальный стандарт для глута?



0



Форумчанин

Эксперт CЭксперт С++

8193 / 5043 / 1437

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

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

29.10.2013, 15:41

11

metaluga145, это не стандарт, но логично запихнуть первичную инициализацию в функцию инициализации.



0



243 / 244 / 38

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

Сообщений: 927

29.10.2013, 15:43

12

MrGluck, оно то логично, но в плюсах ведь не обязательно так делать. или я что-то упустил в этой жизни?



0



46 / 46 / 18

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

Сообщений: 183

29.10.2013, 15:59

 [ТС]

13

Как-то всё равно не понял, почему обязательно в main (ну или в инициализации, что, в свою очередь, тоже в main). Но методом тыка помогли. Спасибо.



0



243 / 244 / 38

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

Сообщений: 927

29.10.2013, 16:01

14

Hunter13ua, я так понял, что не обязательно в main. можно в любую другую функцию, но главное, чтобы в функцию

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



0



46 / 46 / 18

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

Сообщений: 183

29.10.2013, 16:04

 [ТС]

15

Как бы понятно, что в «любой» функции т.к. «любая» функция будет вызвана именно внутри main, что равноценно описанию прямо в main.



0



148 / 114 / 21

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

Сообщений: 266

29.10.2013, 16:07

16

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

Как бы понятно, что в «любой» функции т.к. «любая» функция будет вызвана именно внутри main, что равноценно описанию прямо в main.

Не по теме:

WTF am I reading?



0



Форумчанин

Эксперт CЭксперт С++

8193 / 5043 / 1437

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

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

29.10.2013, 16:17

17

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

MrGluck, оно то логично, но в плюсах ведь не обязательно так делать. или я что-то упустил в этой жизни?

Я выше написал

Порядок создания глобальных переменных неопределен

Сначала идет попытка обращения к t.x а только потом его создание.

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

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

Как бы понятно, что в «любой» функции т.к. «любая» функция будет вызвана именно внутри main, что равноценно описанию прямо в main.

Правильнее будет сказать, что обязательно поместить эти инструкции до точки входа в программу (не чисто физически, над main ) а именно сделать так, чтобы их вызов был явно позже создания объектов, с которыми они работают.

Да и вообще, глобальные переменные — зло. Я понимаю, что в графике их используют чаще, но все же их можно и желательно избегать.



2



Hunter13ua

46 / 46 / 18

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

Сообщений: 183

29.10.2013, 16:18

 [ТС]

18

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

Не по теме:

WTF am I reading?

C++
1
2
3
4
5
int main(){
    int a = 5;
    cout << a;
    return 0;
}

Равноценно

C++
1
2
3
4
5
6
7
8
9
void f(void){
    int a = 5;
    cout << a;
}
 
int main(){
    f();
    return 0;
}

Нет? Может, я выразил мысль криво. Тогда уж извините.



0



MrGluck

29.10.2013, 16:18

Не по теме:

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

WTF am I reading?

правильно WTF I am reading?



0



46 / 46 / 18

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

Сообщений: 183

29.10.2013, 16:19

 [ТС]

20

MrGluck, большое спасибо! Вот теперь понятно



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

29.10.2013, 16:19

Помогаю со студенческими работами здесь

Ошибка expected constructor, destructor, or type conversion before ‘(‘ token
Извините за глупый вопрос, но всё же возникает ошибка
expected constructor, destructor, or type…

Ошибка: «expected constructor, destructor, or type conversion before ‘(‘ token»
connect(CommandLinkButton,clicked(),MainWindow,MainWindow::knopka());
Выдаёт ошибку expected…

Expected constructor, destructor, or type conversion before «void»
Народ. Привет всем. Проблема такая…есть текст программы на С. Вот ее начальный кусок:

#include…

Expected constructor, destructor, or type conversion before «initwindow»
Помогите:Установила Си. Почему программы не компилируются? Пишет: …

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

20

У меня есть ошибка: ожидаемый конструктор, деструктор или преобразование типов до маркера ‘(’. Я не уверен, чего он ожидает, так как он выглядит нормально, но явно нет. Спасибо, все

Вот ошибка

account.cpp:16:14: error: expected constructor, destructor, or type conversion before ‘(’ token
account::acct(num, int_balance) {
^
account.cpp:22:17: error: expected constructor, destructor, or type conversion before ‘(’ token
account::deposit(amount) {

Заголовочный файл

//account.h

#ifndef account_h_
#define account_h_

#include <string>
#include <iostream>

using namespace std;

class account
{
public:
//----------------------------------------------------
//account
int acct(int num, float int_balance);
//----------------------------------------------------
//account number
int account_num() const {
return acctnum;
}
//----------------------------------------------------
//constructs bank account with inital_balance
double balance() const {
return bal;
}
//----------------------------------------------------
//deposit into account
void deposit(float amount) {
bal += amount;
}
//----------------------------------------------------
//withdrawal from account
void withdraw(float amount) {
amount - bal;
}
private:
//----------------------------------------------------
//account number
int acctnum;
//----------------------------------------------------
//balance
double bal;
};

#endif

файл программы

//account.cpp

#include <string>
#include <iostream>

using namespace std;

#include "account.h"
//----------------------------------------------------
//Account details
account::acct(num, int_balance) {
acctnum = num;
bal = int_balance;
}
//----------------------------------------------------
//Depositing into account
account::deposit(amount) {
if (amount < 0) {
std::cout << endl <<"The deposit you've enter is negative."<< amount << " on account " << acctnum << endl;
}
else {
balance = amount;
}
}
//----------------------------------------------------
//Withdrawing from account
//If withdrawel exceeds balance provide error and leave balance
//Else subtract withdrawel from account and update balance
account::withdraw(amount) {
if (amount < balance) {
std::cout << "Debit amount exceeded account balance."<< amount << " on account "<< acctnum << " with balance "<< balance << endl;
}
else if(amount < 0) {
std::cout <<"The withdrawel you've enter is defined as negative."<< amount << " on account "<< acctnum << " with balance "<< balance << endl;
}
else {
balance -= amount;
}
}
//----------------------------------------------------
//Insert intial balance of account
//If no balance included then give error message and set account balance to 0
account::int_balance(float amount){
if (amount >= 0) {
balance = amount;
}
else {
balance = 0;
std::cout << "Error intial balance invalid" << endl;
}
}
//----------------------------------------------------
account::balance(){
return bal;
}

-3

Решение

В своей реализации функции вы забыли указать типы параметров:

Например

account::acct(num, int_balance) {

должно быть

account::acct(int num, float int_balance) {

Кстати: account :: acct не является конструктором. Конструктор должен иметь то же имя, что и класс, и не должен иметь возвращаемого значения.

1

Другие решения

Других решений пока нет …

Arduino.ru

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

duration = pulseIn(echoPin, HIGH);

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

const int Trig = 8;

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

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

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

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

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

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

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

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

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

После void loop() <

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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

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

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

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

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

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

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

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

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

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

ir_code = (ir_code Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Источник

Arduino.ru

ошибка expected constructor, destructor, or type conversion before ‘;’ token в строке Sonar_init(int Tr, int Ec)

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

В строке 3 ‘void’ перед именем функции.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

теперь пишет ошибка компиляции для платы Arduino uno

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

А где весь скетч ?

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

теперь пишет ошибка компиляции для платы Arduino uno

какая ошибка? приведите сообщение об ошибке полностью.

И да. скетч нужно выложить весь.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

У меня вполне компилируется.

Если конечно добавить луп с сетапом и правильно функции вызывать.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

теперь пишет ошибка компиляции для платы Arduino uno

Брехня, я тоже компилировал у себя с лупом и сетапом (пустыми). Приведи ошибку текстом (всю).

Источник

DIY Robotics Lab

Correcting Arduino Compiler Errors

(Intended) Errors and Omissions

What happens after you select the Arduino menu item Sketch -> Verify/Compile and you get error messages that your program failed to compile properly. Sometimes the compiler warnings help you spot the problem code. Other times the error messages don’t make much sense at all. One way to understand the error messages is to create some intentional errors and see what happens.

Create a new program named: LEDBlink_errors

This is one time when it is better to copy the following code so we don’t introduce more errors into the program than are already there.

If you run Verify/Compile command you should see a number of compiler error messages at the bottom of the dialog display.

Arduino Compiler Error Messages

Line 1 Error

Uncaught exception type:class java.lang.RuntimeException

java.lang.RuntimeException: Missing the */ from the end of a /* comment */

/*— Blink an LED —//

The error messages go on for several more lines without adding much information to help solve the problem. You will find a clue to the problem above the compiler message box stating:

Missing the */ from the end of a /* comment */“.

The article “Introduction to Programming the Arduino” describes the comment styles used by C programs. The error on line 1 is caused by mixing the comment styles. The comment begins with the “/*” characters but ends with “//” instead of the “*/” characters. Correct the line as follows:

/*— Blink an LED —*/

Now, rerun the Verify/Compile command.

Line 4 Error

error: stray ‘’ in program

int ledPin = 23; \We’re using Digital Pin 23 on the Arduino.

This is another problem with incorrect commenting technique. In this line the “\” characters are used to begin a comment instead of the “//” characters. The correct line follows:

int ledPin = 3; //We’re using Digital Pin 3 on the Arduino.

Now, rerun the Verify/Compile command.

Line 6 Error

error: expected unqualified-id before ‘<’ token

void setup();

This is an easy mistake to make. The problem is the semicolon “;” at the end of a function declaration. The article “Learning the C Language with Arduino” contains a section about correct usage of semicolons. To correct this problem remove the semicolon as shown below:

void setup()

Now, rerun the Verify/Compile command.

Line 8 Error

In function ‘void setup()’:

error: expected `)’ before numeric constant/home/myDirectory/Desktop/myPrograms/arduino-0015/hardware/cores/arduino/wiring.h:102:

error: too few arguments to function ‘void pinMode(uint8_t, uint8_t)’ At global scope:

pinMode(ledPin OUTPUT); //Set up Arduino pin for output only.

The clue to this problem is found in the message error: too few arguments to function ‘void pinMode(uint8_t, uint8_t)’“. The message includes a list of the function’s arguments and data types (uint8_t). The error is complaining that we have too few arguments. The problem with this line of code is the missing comma between ledPin, and OUTPUT. The corrected code is on the following line:

pinMode(ledPin, OUTPUT); //Set up Arduino pin for output only.

Now, rerun the Verify/Compile command.

Line 11 Error

error: expected constructor, destructor, or type conversion before ‘(’ token

loop()

In this line the type specifier for the function is missing.

To fix this problem place the data type for the function’s return type. In this case we’re not returning any value so we need to add the keyword void in front of the loop function name. Make the following change:

void loop()

Now, rerun the Verify/Compile command.

Line 12 Error

error: function ‘void loop()’ is initialized like a variable

The block of code that makes up the loop function should be contained within curly braces “<“ and “>”. In this line a left parenthesis character “(“ is used instead of the beginning curly brace “<“. Replace the left parenthesis with the left curly brace.

Now, rerun the Verify/Compile command.

Line 13 Error

error: expected primary-expression before ‘/’ token At global scope:

/The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.

This line is supposed to be a comment describing what the program is doing. The error is caused by having only one slash character “/” instead of two “//”. Add the extra slash character then recompile.

//The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.

Line 14 Error

error: ‘high’ was not declared in this scope At global scope:

digitalWrite(ledPin, high); //Setting a digital pin HIGH turns on the LED.

This error message is complaining that the variable “high” was not declared. Programming in C is case sensitive, meaning that it makes a difference if you are using upper or lower case letters. To solve this program replace “high” with the constant value “HIGH” then recompile.

digitalWrite(ledPin, HIGH); //Setting a digital pin HIGH turns on the LED.

Line 15 Error

error: expected `;’ before ‘:’ token At global scope:

delay(1000): //Get the microcontroller to wait for one second.

This error message is helpful in identifying the problem. This program statement was ended with a colon character “:” instead of a semicolon “;”. Replace with the proper semicolon and recompile.

delay(1000); //Get the microcontroller to wait for one second.

Line 16 Error

error: expected unqualified-id before numeric constant At global scope:

digitalWrite(ledPin. LOW); //Setting the pin to LOW turns the LED off.

This error can be particularly troublesome because the comma “,” after the variable ledPin is actually a period “.” making it harder to spot the problem.

The C programming language allows you to build user defined types. The dot operator (period “.”) is part of the syntax used to reference the user type’s value. Since the variable ledPin is defined as an integer variable, the error message is complaining about the unqualified-id.

digitalWrite(ledPin, LOW); //Setting the pin to LOW turns the LED off.

Line 17 Error

In function ‘void loop()’:

error: ‘Delay’ was not declared in this scope At global scope:

Delay(1000); //Wait another second with the LED turned off.

This error was caused by the delay function name being spelled with an incorrect upper case character for the letter “d”. Correct the spelling using the lower case “d” and try the Sketch Verify/Compile again.

delay(1000); //Wait another second with the LED turned off.

Line 18 Error

error: expected declaration before ‘>’ token

There is an extra curly brace at the end of this program. Delete the extra brace to correct this error.

Now, rerun the Verify/Compile command.

Success (or so it seems)

The compiler completed without any more error messages so why doesn’t the LED flash after loading the program on my Arduino?

Line 4 Error

No error message was given by the compiler for this problem.

int ledPin = 23; \We’re using Digital Pin 23 on the Arduino.

The Digital pins are limited to pin numbers 0 through 13. On line 4 the code is assigning a non-existant pin 23 to the ledPin variable. Change the pin assignment to pin 3 and the program should compile, upload to your Arduino and flash the LED if everything is wired properly on your breadboard.

int ledPin = 3; \We’re using Digital Pin 3 on the Arduino.

(c) 2009 – Vince Thompson

Like this:

This entry was posted on June 5, 2009 at 3:54 pm and is filed under Arduino. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Correcting Arduino Compiler Errors”

[…] Robotics Lab Bringing Robotics Home « Microcontrollers as Time Keepers Correcting Arduino Compiler Errors […]

Nice, thank you.
The “stray ‘’ in program” error can also occurs if there’s an accent (like è) in the name of a function.

Источник

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Fifa manager 14 ошибка разрешения
  • Expected before token ошибка ардуино