Error call to non static member function without an object argument

I am working on a project for my intro to c++ class which is to build a program to calculate various statistics. I have the calculations down, but our professor wants us to use std::istream to coll...

I am working on a project for my intro to c++ class which is to build a program to calculate various statistics. I have the calculations down, but our professor wants us to use std::istream to collect the input from a file. The program will keep collecting information from the file until it reaches an End of File marker. I am very unfamiliar with the way std::istream works and I keep encountering this error when I try to compile.

main.cpp:5:10: error: call to non-static member function without an
object argument stats::getInput(std::cin);

Here is my stats.cpp file:

#include "stats.h"
#include <vector>
#include <cstdlib>
#include <iostream>

stats::stats(){
}

std::vector <double> stats::getInput(std::istream& input_stream){

  std::vector <double> stream;
  double x;

  while(input_stream){

    input_stream >> x;
    // std::cout << "your list of numbers is: " << x << std::endl;

    if(input_stream){
      stream.push_back(x);
    }

  }

  return stream;
}

Here is my header file:

#ifndef _STATS_
#define _STATS_
#include <vector>
#include <cstdlib>

class stats{

 public:
  stats();
  std::vector <double> getInput(std::istream& input_stream);

 private:



};

#endif

and here is my main.cpp file:

#include "stats.h"
#include <iostream>

int main(){
  stats::getInput(std::cin);
}

Like I said, I am a beginner in c++ so the answer is probably fairly simple, but c++ is vastly different than Python. I have seen similar questions, but none of them have helped me figure it out.

Thanks

MetMark

6 / 3 / 0

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

Сообщений: 398

1

Ошибка при вызове метода

06.07.2019, 20:42. Показов 3786. Ответов 17

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


Доброго времени суток.
Где-то в файле mainwindow.cpp в слоте я пишу:

C++ (Qt)
1
DraftsmanCube::diagonalA_C();

В этом методе diagonalA_C отрисовывается диагональ А-С с помощью QPainter, но отсюда он не вызывается… Шо не так?

Error

mainwindow.cpp:331:40: error: call to non-static member function without an object argument

Этот метод я расписал в public: в class DraftsmanCube. Т.е. там и сам метод объявлен и тело метода там же написал

P.S. Дописал в DraftsmanCube.h к void diagonal… «static», у указателя убрал (this) (потому что на него ругался…) и ошибки пропали, но он не рисует теперь…

На сколько я понимаю сейчас, весь косяк в том, что он не понимает на чем ему рисовать, но без static в файле mainwindow.cpp метод не вызывается…

C++ (Qt)
1
2
3
4
5
6
    static void diagonalA_C(){
        QPainter *DrawDiagonal = new QPainter();
        DrawDiagonal->setPen(QPen(Qt::red, 3, Qt::SolidLine));
        DrawDiagonal->drawLine(QLineF(QPointF(10, 125), QPointF(125,87))); //A-C
        delete DrawDiagonal;
    }
C++ (Qt)
1
2
3
4
                    if (itemData[i]->text() == "Диагональ")
                    {
                        DraftsmanCube::diagonalA_C();
                    }

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



0



peter_irich

308 / 168 / 46

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

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

06.07.2019, 21:36

2

Вы посмотрите примеры, как работает QPainter.
Для начала пишут либо

C++ (Qt)
1
QPainter *DrawDiagonal = new QPainter(this);

либо

C++ (Qt)
1
DrawDiagonal->begin(this);

а если не this, то на чём он рисует, а после завершения рисования надо вызвать

C++ (Qt)
1
DrawDiagonal->end();



0



6 / 3 / 0

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

Сообщений: 398

06.07.2019, 21:41

 [ТС]

3

peter_irich, Перечитайте сообщение, я там ваше предложение объяснил



0



308 / 168 / 46

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

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

06.07.2019, 21:53

4

Да, действительно, но почему не объявить и создать эту функцию в mainwindow.cpp?
Или где хотите, но тогда рисуйте, например, в объекте типа QPixmap, а потом выводите
его в своём paintEvent().



0



MetMark

6 / 3 / 0

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

Сообщений: 398

06.07.2019, 22:47

 [ТС]

5

peter_irich, DraftsmanCube — это отдельный собственный Widget у которого не функция, а метод diagonalA_C

Немного поразбирался в static и понял, что он сюды не подходит. Мне нужно вызвать метод класса DraftsmanCube::diagonalA_C(), чтобы он выполнился для уже существующего объекта который называется у меня *Cube. Как направить этот метод именно для этого объекта я не понимаю

Решение — написал такую строчку, но от этого метод не начал рисовать…

C++ (Qt)
1
Cube->diagonalA_C();

В отладчике посмотрел, через эту строчку проходит, все норм, но почему-то не рисует…

На сколько я понимаю, нужно как-то в методе указать, что надо рисовать на *Cube, но только как?



0



308 / 168 / 46

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

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

06.07.2019, 23:16

6

Я не знаю, в чём заключается различие между функцией и методом, но в любом случае можно вызвать
функцию одного класса из другого с параметром, вот и передавайте по ссылке объект QPixmap
или в чём хотите рисовать, а потом выводите его у себя. Соответственно ваш QPainter должен быть
не от this, а от этого QPixmap.



0



MetMark

6 / 3 / 0

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

Сообщений: 398

06.07.2019, 23:33

 [ТС]

7

peter_irich, Вы все равно не так немного поняли, но я использовал вашу идею. Выдало в консоль вот это
QWidget:aintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::setPen: Painter not active
А получилось вот так:

C++ (Qt)
1
Cube->diagonalA_C(*Cube);

а в методе написал:

C++ (Qt)
1
2
3
void diagonalA_C(DraftsmanCube &ptr){
....
}

И в качестве родителя QPainter принимает &ptr

Случайно никаких методов перерисовки моего Widget-а вызывать не надо?



0



308 / 168 / 46

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

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

07.07.2019, 08:41

8

Я же всё равно не знаю, что такое Cube, т.е. что представляет собой его класс.
В любом случае над рисовать в том, в чём может рисовать QPainter, полного списка я на память не знаю.
Рисуйте в методе в QPixmap, а в Cube передавайте уже его в paintEvent() и пусть он сам его отрисовывает
как целое. Если это неудобно или нежелательно, то сделайте Cube таким, чтобы Qpainter мог в нём рисовать
без проблем. Сейчас же это как-то происходит.

Если виджет находится на экране, то принудительно его перерисовывать не надо, для него достаточно,
чтобы он был видимым. Перерисовывать надо то, что выводится в paintEvent().



0



Анна по жизни

283 / 172 / 62

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

Сообщений: 416

07.07.2019, 11:54

9

C++ (Qt)
1
2
3
4
if (itemData[i]->text() == "Диагональ")
                    {
                        DraftsmanCube::diagonalA_C();
                    }

Отрисовка должна происходить в методе DraftsmanCube:aintEvent(), следовательно, именно там должен вызываться метод diagonalA_C() . В mainWindow должно указать конкретному экземпляру:»С этого момента ты должен отрисовывать диагональ АС», но не вызывать его метод отрисовки (тем более, в этом случае диагональ отрисуется один раз, а при следующем вызове DraftsmanCube:aintEvent() она затрётся)

У DraftsmanCube должен быть метод, через который у экземпляра взведётся.снимается флажок, ответственный за отрисовку диагонали. А сама отрисовка должна происходить в paintEvent().
Кстати, не стоит каждый раз создавать и удалять объект QPainter, может, лучше передавать его в качестве аргумента: DraftsmanCube::diagonalA_C(QPainter *painter).



0



308 / 168 / 46

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

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

07.07.2019, 16:35

10

У меня в одной программе может использоваться либо свой paintEvent(), либо paintEvent() в другом виджете,
Этот виджет является экземпляром другого класса, его экземпляр создаваётся в главной программе и,
когда надо, делается видимым, а помещён он на то же место, на котором рисует собственный paintEvent().
У него нет рамки и прочего, что обычно есть у окна. При такой схеме трудностей или вопросов с тем,
на чём рисовать.



0



6 / 3 / 0

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

Сообщений: 398

07.07.2019, 17:38

 [ТС]

11

Анна по жизни, После создания объекта и расположения на форме у меня отрисовывается моя фигура в :aintEvent(QPaintEvent *); Если в :aintEvent(QPaintEvent *); произойдут изменения он Painter перерисует?

Цитата
Сообщение от Анна по жизни
Посмотреть сообщение

С этого момента ты должен отрисовывать диагональ АС

virtual void paintEvent(QPaintEvent *); — находится в protected, доступ получить не могу.



0



308 / 168 / 46

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

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

07.07.2019, 18:13

12

Я удивляюсь, вы берётесь создавать программы в Qt и не знаете, что делать с функциями из protected.
Посмотрите всё же примеры программ.

Выше ошибка, должно быть так:
При такой схеме трудностей или вопросов с тем, на чём рисовать, нет.



0



MetMark

6 / 3 / 0

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

Сообщений: 398

07.07.2019, 18:40

 [ТС]

13

Проще говоря. Как вызвать из файла .cpp класса MainWindow, virtual void paintEvent(QPaintEvent *); который объявлен в protected класса DraftsmanCube?

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

Я удивляюсь, вы берётесь создавать программы в Qt и не знаете, что делать с функциями из protected.

Объясните, ну пожааааааалуйста, очень вас прошу. Не понимаю то, что написано в примерах

Единственное что я могу предположить, это то, что мне нужно унаследовать MainWindow от DraftsmanCube и тогда я смогу вызвать все что угодно из protected

В mainwindow.cpp у меня есть следующие строчки:

C++ (Qt)
1
2
3
4
5
6
7
8
if (ThisIsText == "Диагональ") //Логика программы (Если диагональ пользователь выбрал, то true)
{
      Cube->diagonalA_C(); /*Вызывается метод (Там он устанавливает значение bool переменной на true, а в painEvent у 
DraftsmanCube есть строчка, где при значении этой переменной true рисуется диагональ) который я объявил в DraftsmanCube в 
public. Вызывается без ошибок только так, в остальных случаях выдает разные ошибки. Cube это указатель на объект класса 
DraftsmanCube который уже создан и во всю работает в программе*/
      Cube->paintEvent(); //Как вызвать метод paintEvent не знаю ибо постоянно на меня обваливаются ошибки....
}



0



308 / 168 / 46

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

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

07.07.2019, 19:30

14

Неправильно предполагаете. Возьмите толстую книгу, лучше в электронном виде, и почитайте,
там и обучение и примеры. Обычно рекомендуют книгу «Макс Шлее, Qt 5.3».
А как вызвать, я написал выше в сообщении от 16.35.



0



6 / 3 / 0

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

Сообщений: 398

07.07.2019, 19:37

 [ТС]

15

peter_irich, Про QPainter и про QPaintEvent я читал уже в этой книге. Можете просто написать, как в моем случае должно сработать? Пожалуйста



0



308 / 168 / 46

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

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

07.07.2019, 20:14

16

Я не знаю, как у вас должно сработать, т.к. не знаю вашей программы.
Если в этой книге вы читали о paintEvent(), то должны знать, как к ней обращаться.
Возьмите ещё Жасмин Бланшет, Марк Саммерфилд » Qt 4: программирование GUI на C++»,
там примеры с разъяснениями. Когда мне в начале 2000-х потребовалось научиться создавать программы на Qt,
так я откуда-то из США выписал книгу на английском, кажется, ещё по Qt 2, чек туда посылал, посмотрел и начал работать.
За вас вашу работу делать никто не будет и чтобы научиться, надо самому пробовать, а не воспроизводить
чужие советы.



0



283 / 172 / 62

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

Сообщений: 416

08.07.2019, 11:29

17

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

virtual void paintEvent(QPaintEvent *); — находится в protected, доступ получить не могу.

И не надо.

Установи флажок, по которому Cube будет рисовать диагональ, и вызови Cube->update().

Добавлено через 7 минут
https://doc.qt.io/qt-5/qtwidge… mple.html#
Посмотри пример. Тут update() вызывается каждую секунду, чтобы перерисовать стрелки часов.



0



6 / 3 / 0

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

Сообщений: 398

08.07.2019, 11:53

 [ТС]

18

Анна по жизни, Да, я новую тему создал и уже догадался. Спасибо вам большое! Есть же добрые люди!!! Спасибо огромное вам!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

08.07.2019, 11:53

18


error: calls a non-static member function with no object arguments.
this error occurs because the class is not instantiated with .
Take a chestnut, for example:

 class Student
 {
 public:
 int getAge();
 };

The reason for this error may be that when you call the function getAge(), you are doing this:

 Student::getAge();

Or do it this way:

  Student.getAge();

This means that the member function is called without instantiating the class Student.
Fix one: Instantiate an object first

 Student XiaoWang;
 int age = XiaoWang.getAge();

Correction 2: Declare member functions as static functions

 class Student
 {
 public:
static  int getAge(); 
 };
 
 Student::getAge();

Take chestnuts, for example:


  QDir::mkpath(Path);

Error: Calling a non-static member function with no object arguments.
the reasons for this error is that the class does not instantiate and call mkpath function need to first class instantiation,
to:

   QDir tempDir;   
    tempDir.mkpath(Path); 

That’s right.
If you write your own class, you can also add the static keyword before the function’s declaration in the class body to declare the function as a static member and call it without instantiation.
such as:


QMessageBox::warning(this,tr("Warning"),tr("No Exist"));

Static member functions can be called directly with “ class :: function name “.

Read More:

This topic has been deleted. Only users with topic management privileges can see it.

  • Hello everyone,
    I am trying to implement Signal&Slots. But I am getting the Error: «call to non static member function without an object argument «

    mainwindow.cpp

    void MainWindow::on_Button_clicked()
    {
        addressEntry *name = new addressEntry();
        name->setName(ui->lineName->text());
    
        connect(addressEntry::setName(name), SIGNAL(entry(QString)), addressReaderWriter::Write(name), SLOT(Write(QString)));
      
    }
    

    addressEntry.cpp

    void addressEntry::setName(QString name)
    {
        mName = name;
        qDebug() << "setName";
        emit entry(name);
    }
    
    QString addressEntry::getName()
    {
        return mName;
    }
    
    

    addressReaderWriter.cpp

    void addressReaderWriter::Write(QString name){
              name.getName();    
    }
    

    Hope Someone can help.

  • Hi,

    Your connect statement is wrong.

    setName is a member function that you are calling like if it was a static function.

    The first and third parameters of connect should be objects.

  • @SGaist Thank you for your reply. I understand the problem, but could you tell me how I can solve it?
    My goal is it to transfer the variable «name->setName(ui->lineName->text());»from void MainWindow::on_btnAdd_clicked() to void addressReaderWriter::Write(QString name){
    by using Signal&Slots

  • Dis you read the documentation of the method ?

    The first parameter shall be the object that will emit the signal and the third the object that will have the slot activated.

  • @SGaist Yes I read it, but I am having trouble to implement it correctly

  • @Chaki

    The first and third parameter needs to be a pointer to your sender / receiver object.
    What you did can not work and I also think you’ve put it in the wrong place.

  • @Chaki said in call to non static member function without an object argument:

    but I am having trouble to implement it correctly

    Then please show what you have now…

  • @jsulm currently I am trying:

    mainwindow.cpp:

    void MainWindow::on_btnAdd_clicked()
    {
        addressEntry *name = new addressEntry();
        name->**setName**(ui->lineEdit->text());
    
        
        connect(&name, SIGNAL(addressEntry::entry(QString)), addressReaderWriter::Write(name), SLOT(addressReaderWriter::Write(QString)));
    
      
    }
    

    addressentry.h:

    signals:
        void entry(QString name);
    
    

    addressentry.cpp:

    
    void addressEntry::setName(QString name)
    {
        mName = name;
        emit entry(name);
    
    }
    
    

    addressReaderWriter.h:

    public slots:
        void Write(QString);
    

    addressReaderWriter.cpp

    void addressReaderWriter::Write(QString name){
      name.getName();
    
    
         
    }
    
  • Your signal/slot signatures in the connect() are wrong. Please read https://doc.qt.io/qt-5/signalsandslots.html before using something.

  • @Christian-Ehrlicher I know that the connect is wrong and I have read the Docu, but I am having trouble using it correctly

  • There is so much wrong in your code I don’t even know where to start. I would suggest you to start with one of the Qt examples and learn c++ — sorry.

  • @Chaki said in call to non static member function without an object argument:

    I have read the Docu

    If you did then why are you still doing it wrongly? Your code does not even make sence to be honest.

    connect(name, &addressEntry::entry, addressReaderWriterInstancePtr, &addressReaderWriter::Write);
    

    addressReaderWriterInstancePtr would be a pointer to an instance of addressReaderWriter which you want to react on the signal.

  • This post is deleted!

  • @MalitheBIG said in call to non static member function without an object argument:

    Thats not how you treat new useres who try to get into QT.

    Before you learn Qt you have to learn c++, thats the reality — sorry.

  • This post is deleted!

  • This post is deleted!

  • @MalitheBIG Da stimme ich Ihnen zu

  • @MalitheBIG That’s true, maybe try and help him instead of just calling him stupid

  • This post is deleted!

  • I have spent a few hours working on this and am finally down to three errors «call to non-static member function without an object argument. The errors are in both of the display functions. Any help is greatly appreciated

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    Header file:
    
    //
    //  Date.h
    //  Date class with constructor with default arguments
    //  Member functions defined in Date.cpp
    //  C++ Programming
    //  Fall 2014
    //  Paul XXXXXXXXX
    //
    //
    
    #ifndef Paul_Date_H
    #define Paul_Date_H
    
    #include <string>
    using std::cout;
    using std::endl;
    using std::setfill;
    using std::setw;
    using std::string;
    using namespace std;
    
    class Date
    {
    public:
    
        // default constructor setting date to January 1, 2000
        explicit Date ( int = 1, int = 1, int=2000 );
        
        // set functions
        // function to set date
        void setDate( int, int, int ); //set date DD/MM/YYYY
        
        // function to set day
        void setDay( int );  //set day
        
        // function to set month
        void setMonth( int ); // set month
        
        // function to set month name
        void setMonthName(string);  // set month name
        
        // function to set year
        void setYear( int); // set year
        
        // get functions
        
        // function to return the day value of the class Date
        int getDay() const; // return day value
    
        // function to return the month value of the class Date
        int getMonth() const; //return month value
        
        // function to get month Name
        string getMonthName() const; // return the name of the month
        
        // function to return the year value of the class Date
        int getYear() const; // return year value
    
        // function to display Date in DD/MM/YYYY format including leading 0 where needed
         void displayNumericDate();
       
        // function to display date in long date eg. 1 January, 1900
        void displayLongDate();
        
    private:
        
        int month;
        int day;
        int year;
    
    };  // end of class Date
    
    #endif /* defined(Paul_Date_H) */
    
    __________________________________________________________________
    
    Source code:
    
    // Date.cpp
    //
    // C++ Programming
    // Fall 2014
    // Paul XXXXXXXXXX
    
    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <array>
    #include "Date.h"
    
    
    
    
    array< const int, 12> numberOfDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    array < const string, 12> monthName = { "January", "February", "March", "April", "May",
        "June", "July", "August", "September", "October", "November", "December"};
    
    // Date constructor with arguments and validation
    Date::Date( int day, int month, int year)
    {
        setDate( day, month, year ); //validate and set date
    }  // end Date constructor
    
    // set date value
    void Date::setDate( int d, int m, int y)
    {
        setDay( d ); // get private field day
        setMonth( m ); //get private field month
        setYear( y ); // get private field year
    }  // end function setDate
    
    void Date::setDay ( int d)
    {
        if ( d >= 1 && d <= numberOfDays[ month - 1] )
            day = d;
        else
            day = 1;
    } // end of setDay function
    
    void Date::setMonth (int m)
    {
         month = (m >=1 && m <= 12) ? m : 1;
    }  // end of setMonth function
    
    void Date::setYear(int y)
    {
        year = ( y >= 1900 ? y : 1900 );
    }  // end of setYear function
    
    // return day value
    int Date::getDay() const
    {
        return day;
    } // end of getDay function
    
    // return month value
    int Date::getMonth() const
    {
        return month;
    } // end of getMonth function
    
    // return the month name
    string Date::getMonthName() const
    {
        return monthName[ Date::getMonth()  - 1 ];
    }
    
    // return year value
    int Date::getYear() const
    {
        return year;
    } // end of getYear function
    
    // print date in DD/MM/YYYY format
    void displayNumericDate() 
    {
        cout << setfill( '0' ) << setw( 2 ) << Date::getDay() << "/"
        << setfill( '0') << setw( 2 ) << Date::getMonth()<< "/" << setw( 4 ) << Date::getYear();
    }  // end of displayNumericDate function
    
    // print date in long date format eg. 1 January, 1900
    void displayLongDate()
    {
        cout << Date::getDay() << " " << Date::getMonthName() << ", " << Date::getYear()
    }  // end of displayLongDate
    
    

    Как описано Вот:, Вы можете подключить сигнал к простой функции, например так:

    connect(
    sender, &Sender::valueChanged,
    someFunction
    );
    

    Вот моя программа:

    #include <QCoreApplication>
    #include <QNetworkAccessManager>
    #include <QNetworkReply>
    #include <QNetworkRequest>void handleReply(QNetworkReply *reply)
    {
    QString replyStr = reply->readAll();
    }
    
    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);
    
    QNetworkAccessManager manager;
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
    
    return a.exec();
    }
    

    Однако я получаю несколько ошибок:

    main.cpp:18: error: call to non-static member function without an object argument
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
    ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~
    
    main.cpp:18: error: 'QNetworkReply' does not refer to a value
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
    ^
    main.cpp:18: error: expected expression
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
    ^
    
    main.cpp:18: error: 'QNetworkReply' does not refer to a value
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
    ^
    /usr/include/x86_64-linux-gnu/qt5/QtNetwork/qnetworkreply.h:62: declared here
    class Q_NETWORK_EXPORT QNetworkReply: public QIODevice
    
    main.cpp:18: error: expected expression
    connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
    ^
    ^
    

    Буду признателен за любую помощь. Спасибо.

    0

    Решение

    При использовании нового синтаксиса соединения указывать тип аргументов не обязательно, поэтому просто используйте:

    #include <QCoreApplication>
    #include <QNetworkAccessManager>
    #include <QNetworkReply>
    #include <QNetworkRequest>
    
    #include <QDebug>
    
    static void handleReply(QNetworkReply *reply)
    {
    QString replyStr = reply->readAll();
    // do stuff
    qDebug()<< replyStr;
    reply->deleteLater();
    }
    
    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);
    
    QNetworkAccessManager manager;
    QObject::connect(&manager, &QNetworkAccessManager::finished, &handleReply);
    manager.get(QNetworkRequest(QUrl("https://www.google.com")));
    
    return a.exec();
    }
    

    Замечания:
    Вы должны использовать только connect(...) если вы находитесь внутри класса, который наследует от QObject, в случае основного вы должны использовать QObject::connect(...)

    1

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

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

    Понравилась статья? Поделить с друзьями:
  • Error call to abs is ambiguous
  • Error call to a member function get on null
  • Error call to a member function connection on null
  • Error call retries were exceeded
  • Error call of overloaded is ambiguous