Qualified id in declaration 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QDir>
 
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);   // Инициализация интерфейса
 
    playlist_model = new QStandardItemModel;   // Модель для хранения названия треков и путей к ним
 
    playlist_model->setHorizontalHeaderLabels(QStringList() <<  // Заголовки для модели (таблицы):
                                              tr("Playlist") <<    // название файла,
                                              tr("Path"));      // путь к файлу
 
    ui->playlist_table->                       // Подключаем модель к интерфейсу
            setModel(playlist_model);          // (т. е. к таблице playlist_table)
 
    ui->playlist_table->hideColumn(1);         // Скрываем колонку с путём к файлу
 
    ui->playlist_table->horizontalHeader()->   // Растягиваем последний видимый заголовок
            setStretchLastSection(true);       // (т. е. "Track")
 
    player = new QMediaPlayer;        // Создаём плеер (все базовые функции плеера)
    playlist = new QMediaPlaylist;    // Создаём плейлист
 
    player->setPlaylist(playlist);    // Подключаем плейлист к плееру
    player->setVolume(50);            // Постоянная громкость 50
 
    /* --------------------------------------------
       TODO: сделать привязку кнопок и слайдеров
    -------------------------------------------- */
    connect(ui->button_previous, &QPushButton::clicked, playlist, &QMediaPlaylist::previous);
    connect(ui->button_next, &QPushButton::clicked, playlist, &QMediaPlaylist::next);
    connect(ui->button_play, &QPushButton::clicked, player, &QMediaPlayer::play);
    connect(ui->button_pause, &QPushButton::clicked, player, &QMediaPlayer::pause);
    connect(ui->button_stop, &QPushButton::clicked, player, &QMediaPlayer::stop);
 
    slider_time = new QSlider;     // Слайдер для перемотки
 
     // Слайдер для громкости
    slider_volume = new QSlider(Qt::Horizontal, this);
    slider_volume->setRange(0, 100);
    slider_volume->setFixedWidth(100);
    slider_volume->setValue(100);
    player = new QMediaPlayer;
    connect(slider_volume, SIGNAL(valueChanged(int)), this, SIGNAL(volumeChanged(int)));
    connect(this, SIGNAL(volumeChanged(int)), player, SLOT(setVolume(int)));
    int Widget::volume() const //Error
    {
        return slider_volume->value();
    }
 
 
    void Widget::setVolume(int volume) //Error
    {
        player->setVolume(volume);
    }
}
 
Widget::~Widget()
{
    delete ui;
    delete player;
    delete playlist;
    delete playlist_model;
    delete slider_time;
    delete slider_volume;
}
/* -----------------------------
   TODO: сделать выборку файлов
------------------------------- */
/* void Widget::addSongs()
{
    ...
}
*/
  • Forum
  • Beginners
  • qualified-id in declaration before ‘(‘ t

qualified-id in declaration before ‘(‘ token

Write your question here.

hi i am just testing stuff and came across this problem qualified-id in declaration before ‘(‘ token
this is a very small code.. i am a class 0 beginner :P

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
main.cpp

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


int main() {
   
    test tc;
    
    cout << "testing output2" <<endl;
cout<<"..................................................................................."<<endl;    


magic mg;

mg.print();


    return 0;
}

................................................................................
 test.cpp


#include "test.h"


test::test() {
    cout<< "i am a constructor"<<endl;
}



test::~test() { // deconstructor have no parameters and no return value no variables.
    cout<<"i am the deconstructor"<<endl;
}

 
 
magic::magic1(){
    
    void magic::print(){
        
        cout<< "regular function"<<endl;
    }
    
}




................................................................................
test.h

#include <iostream>
using namespace std;

#ifndef TEST_H
#define	TEST_H

class test {
public:
    test();
    ~test(); //deconstructor  
private:
};

class magic{
public:
    magic1();
    void print();
private: 
    
};

#endif	


  

thanks

You don’t give the line of the error, but line 73 looks wrong, if it’s meant to be a constructor, the name must be the same as the class, if it isn’t, it needs a return type. You would then also have to change the definition (line 43). Also the term is destructor not deconstructor and you should put include guards at the very start of header files and don’t use using namespace std; in header files (outside of header files it’s your choice but it’s still not a good idea). There’s also no need to put access identifiers if you aren’t going to put anything after them. Finally, proper indenting of code vastly increases readability.

thanks shadowmouse. very helpful!

Topic archived. No new replies allowed.

Arduino Forum

Loading

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.

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

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

У меня есть два открытых класса; один статический (DesktopOps) один нестатический (Args), и я пытаюсь инициализировать статические переменные статического класса в main.

Я получаю сообщение об ошибке:

main.cpp:25: error: qualified-id in declaration before '=' token
Point DesktopOps::window_coords = Point(arg.topleft_x, arg.topleft_y);
^
main.cpp:26: error: qualified-id in declaration before '=' token
Point DesktopOps::window_dims = Point(arg.width, arg.height);
^

Вот MWE:

#include <opencv2/opencv.hpp>

using namespace cv;

struct Args{
int topleft_x, topleft_y, width, height;

Args(){
topleft_x = topleft_y = width = height = -1;
}
};struct DesktopOps {
static Point window_coords;
static Point window_dims;

};int main(){
Args arg();

Point DesktopOps::window_coords = Point(arg.topleft_x, arg.topleft_y);
Point DesktopOps::window_dims = Point(arg.width, arg.height);
}

10

Решение

Я не очень понимаю, что вы пытаетесь сделать …. но статические переменные должны быть созданы в глобальной области видимости, вне основной функции:

Args arg;
Point DesktopOps::window_coords = Point(arg.topleft_x, arg.topleft_y);
Point DesktopOps::window_dims = Point(arg.width, arg.height);

int main(){

}

Но эта глобальная переменная Args не имеет смысла ….

14

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

В структуре вы объявлять переменные-члены, но когда вы определять их вы не можете сделать это в функции, это должно быть сделано в глобальной области, например,

struct DesktopOps {
static Point window_coords;
static Point window_dims;
};

Point DesktopOps::window_coords = Point(someX, someY);
Point DesktopOps::window_dims = Point(someW, someH);

int main()
{
// ...
}

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

struct DesktopOps {
static Point window_coords;
static Point window_dims;
};

Point DesktopOps::window_coords;
Point DesktopOps::window_dims;

int main()
{
Args arg;

DesktopOps::window_coords = Point(arg.topleft_x, arg.topleft_y);
DesktopOps::window_dims = Point(arg.width, arg.height);
}

6

Возможно, вам также будет интересно:

  • Quake champions код ошибки 161
  • Qt программа завершилась с ошибкой
  • Quake champions код ошибки 104
  • Qt ошибка в moc файле
  • Quake champions код ошибки 103

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

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