Ошибка invalid use of this in non member function

You just tried to copy some code without understanding what was going on.

It looks like you saw a code like this :

#include <QtGui>
#include <QWidget>
 
class MyWidget : public QWidget
{
    Q_OBJECT
public:
 
protected:
    void paintEvent(QPaintEvent *event)
    {
        //create a QPainter and pass a pointer to the device.
        //A paint device can be a QWidget, a QPixmap or a QImage
        QPainter painter(this);   // <- Look at this !!
        //               ^^^^ Allowed    

        // ...
    }

signals:

public slots:
 
};
 
int main( int argc, char **argv )
{
    QApplication app( argc, argv );
 
    MyWidget myWidget;
    myWidget.show();
 
    return app.exec();
}

Here you can see that in the function paintEvent of the class MyWidget we use the this pointer. We can because we use it in a non-static member of the class. Here this is of type MyWidget*.

Look at the standard :

9.3.2 The this pointer [class.this]

In the body of a non-static member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*.

So you cannot use the this pointer inside the main function, this is no sense.

And other thing, like it is said in the comment inside the code, you just have to pass a pointer to a device to the QPainter constructor. It can be a QWidget, a QPixmap or a QImage.

Maybe you should read this for a beginning : http://www.cplusplus.com/doc/tutorial/classes/

  • Forum
  • Beginners
  • Thread invalid use of ‘this’ in non-

Thread invalid use of ‘this’ in non-member function

I’m trying threads for the first time and I’ve run into an error when attempting to implement in main.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
main {
    tm time1;
    //set up time1;
    std::thread t(&Schedule::timeAlert, this, time1);
    t.join();
}

Schedule.h

class Schedule {
  public:
    void timeAlert(tm time);
}

Schedule.cpp

void Schedule::timeAlert(tm time) {
    sleep_until (system_clock::from_time_t (timegm(&time)));
    cout << "It is " << std::asctime(&time);
}

Why is it treating this function like a non-member? It clearly is a member of Schedule…

> Why is it treating this function like a non-member? It clearly is a member of Schedule

main()

is not a member function.
If the function must be non-static, an object of the class type is required.

For example:

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
#include <iostream>
#include <thread>
#include <chrono>
#include <ctime>

struct scheduler {

    void wake_up_and_alert_at( std::time_t time ) const {

        std::this_thread::sleep_until( std::chrono::system_clock::from_time_t(time) ) ;
        std::cout << "alert from " << name << ": it is " << std::ctime( std::addressof(time) );
    }

    std::string name ;
};

int main() {

    const auto now = std::time(nullptr) ;
    std::cout << std::ctime( std::addressof(now) );

    scheduler sch { "scheduler X" } ;
    std::thread t( &scheduler::wake_up_and_alert_at, std::addressof(sch), now+5 ) ;
    t.join() ;
}

OK I set it up like this:

1
2
3
Schedule mySchedule;  
std::thread t(&Schedule::timeAlert, std::addressof(mySchedule), time1);
t.join();

And I got this error:

 In function `std::thread::thread<void (Schedule::*)(tm), Schedule*, tm&>(void (Schedule::*&&)(tm), Schedule*&&, tm&)':
/usr/include/c++/7/thread:122: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

What does this mean?

Last edited on

With the GNU tool chain, the compiler option

-pthread

is required.
For example:

g++ -std=c++17 -O3 -Wall -Wextra -pedantic-errors -pthread my_program.cpp

OK I added it in…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
CXX = g++
CXXFLAGS = -c -g -std=c++11 -Wall -W -Werror -pthread -pedantic
LDFLAGS =

schedule: main.o schedule.o
	$(CXX) $(LDFLAGS) main.o schedule.o -o main

main.o : main.cpp
	$(CXX) $(CXXFLAGS) main.cpp

schedule.o: schedule.cpp schedule.h
	$(CXX) $(CXXFLAGS) schedule.cpp

clean :
	rm -f core $(PROG) *.o

But I’m still getting the same error:

In function `std::thread::thread<void (Schedule::*)(tm), Schedule&, tm&>(void (Schedule::*&&)(tm), Schedule&, tm&)':
/usr/include/c++/7/thread:122: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

I did a make clean first just to be safe, but that didn’t solve it.

Add

-pthread

to the link options too:

LDFLAGS = -pthread

Topic archived. No new replies allowed.

I had working on a class and started writing everything in the same .cpp file. However, after a while I could see the class getting bigger and bigger so I decided to split it into a .h and a .cpp file.

gaussian.h file:

class Gaussian{
    private:
        double mean;
        double standardDeviation;
        double variance;
        double precision;
        double precisionMean;
    public:
        Gaussian(double, double);
        ~Gaussian();
        double normalizationConstant(double);
        Gaussian fromPrecisionMean(double, double);
        Gaussian operator * (Gaussian);
        double absoluteDifference (Gaussian);
};

gaussian.cpp file:

#include "gaussian.h"
#include <math.h>
#include "constants.h"
#include <stdlib.h>
#include <iostream>

Gaussian::Gaussian(double mean, double standardDeviation){
    this->mean = mean;
    this->standardDeviation = standardDeviation;
    this->variance = sqrt(standardDeviation);
    this->precision = 1.0/variance;
    this->precisionMean = precision*mean;
} 

//Code for the rest of the functions...

double absoluteDifference (Gaussian aux){
    double absolute = abs(this->precisionMean - aux.precisionMean);
    double square = abs(this->precision - aux.precision);
    if (absolute > square)
        return absolute;
    else
        return square;
}

However, I can’t get this to compile. I try running:

g++ -I. -c -w gaussian.cpp

But I get:

gaussian.cpp: In function ‘double absoluteDifference(Gaussian)’:
gaussian.cpp:37:27: error: invalid use of ‘this’ in non-member function
gaussian.h:7:16: error: ‘double Gaussian::precisionMean’ is private
gaussian.cpp:37:53: error: within this context
gaussian.cpp:38:25: error: invalid use of ‘this’ in non-member function
gaussian.h:6:16: error: ‘double Gaussian::precision’ is private
gaussian.cpp:38:47: error: within this context

Why can’t I use this?? I am using it in the fromPrecisionMean function and that compiles. Is it because that function returns a Gaussian? Any extra explanation will be really appreciated, I am trying to learn as much as I can! Thanks!

You just tried to copy some code without understanding what was going on.

It looks like you saw a code like this :

#include <QtGui>
#include <QWidget>
 
class MyWidget : public QWidget
{
    Q_OBJECT
public:
 
protected:
    void paintEvent(QPaintEvent *event)
    {
        //create a QPainter and pass a pointer to the device.
        //A paint device can be a QWidget, a QPixmap or a QImage
        QPainter painter(this);   // <- Look at this !!
        //               ^^^^ Allowed    

        // ...
    }

signals:

public slots:
 
};
 
int main( int argc, char **argv )
{
    QApplication app( argc, argv );
 
    MyWidget myWidget;
    myWidget.show();
 
    return app.exec();
}

Here you can see that in the function paintEvent of the class MyWidget we use the this pointer. We can because we use it in a non-static member of the class. Here this is of type MyWidget*.

Look at the standard :

9.3.2 The this pointer [class.this]

In the body of a non-static member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*.

So you cannot use the this pointer inside the main function, this is no sense.

And other thing, like it is said in the comment inside the code, you just have to pass a pointer to a device to the QPainter constructor. It can be a QWidget, a QPixmap or a QImage.

Maybe you should read this for a beginning : http://www.cplusplus.com/doc/tutorial/classes/

  • Home
  • Forum
  • Qt
  • Qt Programming
  • invalid use of this in non member function

  1. 19th January 2011, 11:27

    #1

    hi i want to do a qt mobile apps which using network access but while compiling my code it shows the following errors.

    i. invalid use of this in non member function
    ii. connect was not declared in this scope

    I have do the following in my code:

    .pro file:

    1. QT += network

    To copy to clipboard, switch view to plain text mode 

    main.cpp file

    1. #include <QtGui/QApplication>

    2. #include "mainwindow.h"

    3. #include <QtNetwork>

    4. int main(int argc, char *argv[])

    5. {

    6. MainWindow w;

    7. QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    8. connect(manager, SIGNAL(finished(QNetworkReply*)),

    9. this, SLOT(replyFinished(QNetworkReply*)));

    10. manager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));

    11. #if defined(Q_WS_S60)

    12. w.showMaximized();

    13. #else

    14. w.show();

    15. #endif

    16. return a.exec();

    17. }

    To copy to clipboard, switch view to plain text mode 

    Is it any problem with my code please help me. Thanks.


  2. 19th January 2011, 11:31

    #2

    Default Re: invalid use of this in non member function

    connect() is a method of QObject and not a standalone function.

    1. QObject::connect(manager, SIGNAL(finished(QNetworkReply*)),

    2. this, SLOT(replyFinished(QNetworkReply*)));

    To copy to clipboard, switch view to plain text mode 

    Last edited by wysota; 19th January 2011 at 11:36.

    Your biological and technological distinctiveness will be added to our own. Resistance is futile.

    Please ask Qt related questions on the forum and not using private messages or visitor messages.


  3. The following user says thank you to wysota for this useful post:

    dineshkumar (19th January 2011)


  4. 19th January 2011, 11:37

    #3

    Default Re: invalid use of this in non member function

    hi thanks,
    But it again shows the following error:

    invalid use of this in non member function


  5. 19th January 2011, 11:53

    #4

    Default Re: invalid use of this in non member function

    There is no «this» in main().

    Your biological and technological distinctiveness will be added to our own. Resistance is futile.

    Please ask Qt related questions on the forum and not using private messages or visitor messages.


  6. The following user says thank you to wysota for this useful post:

    dineshkumar (19th January 2011)


  7. 19th January 2011, 11:56

    #5

    Default Re: invalid use of this in non member function

    1. replyFinished(QNetworkReply*)

    To copy to clipboard, switch view to plain text mode 

    where is this function defined? you need that class object to be passed in connect instead of «this», the same as you pass «manager».


  8. The following user says thank you to nish for this useful post:

    dineshkumar (19th January 2011)


  9. 19th January 2011, 14:38

    #6

    Default Re: invalid use of this in non member function

    It is probably easier if you move your code to the MainWindow instead:

    main.cpp:

    1. // main.cpp

    2. #include <QtGui/QApplication>

    3. #include "mainwindow.h"

    4. int main(int argc, char *argv[])

    5. {

    6. MainWindow w;

    7. #if defined(Q_WS_S60)

    8. w.showMaximized();

    9. #else

    10. w.show();

    11. #endif

    12. return a.exec();

    13. }

    To copy to clipboard, switch view to plain text mode 

    mainwindow.h:

    1. // mainwindow.h

    2. #ifndef MAINWINDOW_H

    3. #define MAINWINDOW_H

    4. #include <QtGui/QMainWindow>

    5. class QNetworkReply;

    6. {

    7. Q_OBJECT

    8. public:

    9. explicit MainWindow(QWidget *parent = 0);

    10. ~MainWindow();

    11. protected slots:

    12. void replyFinished(QNetworkReply *reply);

    13. };

    14. #endif // MAINWINDOW_H

    To copy to clipboard, switch view to plain text mode 

    mainwindow.cpp

    1. // mainwindow.cpp

    2. #include <QtNetwork/QtNetwork>

    3. #include <QtNetwork/QNetworkReply>

    4. #include "mainwindow.h"

    5. #include <QDebug>

    6. {

    7. QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    8. connect(manager, SIGNAL(finished(QNetworkReply*)),

    9. this, SLOT(replyFinished(QNetworkReply*)));

    10. manager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));

    11. }

    12. MainWindow::~MainWindow()

    13. {

    14. }

    15. void MainWindow::replyFinished(QNetworkReply *reply)

    16. {

    17. qDebug() << "ok!";

    18. }

    To copy to clipboard, switch view to plain text mode 


  10. The following 2 users say thank you to helloworld for this useful post:

    dineshkumar (20th January 2011), tylor2000 (13th December 2015)


  11. 20th January 2011, 06:19

    #7

    Default Re: invalid use of this in non member function

    Thankyou friend its works..


  12. 13th December 2015, 20:37

    #8

    Post Re: invalid use of this in non member function

    Thank you helloworld, this helped me out a lot. You will probably never see this but just wanted to thank you for the code example. It’s still helping people out after all these years.


Similar Threads

  1. Replies: 0

    Last Post: 24th October 2010, 20:09

  2. Replies: 3

    Last Post: 8th July 2010, 14:12

  3. Replies: 4

    Last Post: 29th July 2009, 16:23

  4. Replies: 22

    Last Post: 8th October 2008, 14:54

  5. Replies: 4

    Last Post: 19th June 2006, 16:21

Bookmarks

Bookmarks


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.

Вы просто пытались скопировать какой-то код, не понимая, что происходит.

Похоже, вы видели такой код:

#include <QtGui>
#include <QWidget>
 
class MyWidget : public QWidget
{
    Q_OBJECT
public:
 
protected:
    void paintEvent(QPaintEvent *event)
    {
        //create a QPainter and pass a pointer to the device.
        //A paint device can be a QWidget, a QPixmap or a QImage
        QPainter painter(this);   // <- Look at this !!
        //               ^^^^ Allowed    

        // ...
    }

signals:

public slots:
 
};
 
int main( int argc, char **argv )
{
    QApplication app( argc, argv );
 
    MyWidget myWidget;
    myWidget.show();
 
    return app.exec();
}

Здесь вы можете видеть, что в функции paintEvent класса class MyWidget мы используем this указатель. Мы можем, потому что мы используем его в нестатическом члене класса. Здесь this имеет тип MyWidget*.

Посмотрите стандарт:

9.3.2 Указатель this [class.this]

В разделе тело нестатической функции-членаключевое слово this является выражением prvalue, значением которого является адрес объекта, для которого вызывается функция. Тип this в функции-члене класса X — X*.

Таким образом, вы не можете использовать this указатель внутри main функция, в этом нет смысла.

И еще, как сказано в комментарии внутри кода, вам просто нужно передать указатель на устройство в QPainter конструктор. Это может быть QWidget, чтобы QPixmap или QImage.

Может быть, вы должны прочитать это для начала: http://www.cplusplus.com/doc/tutorial/classes/

  • Forum
  • Beginners
  • Thread invalid use of ‘this’ in non-

Thread invalid use of ‘this’ in non-member function

I’m trying threads for the first time and I’ve run into an error when attempting to implement in main.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
main {
    tm time1;
    //set up time1;
    std::thread t(&Schedule::timeAlert, this, time1);
    t.join();
}

Schedule.h

class Schedule {
  public:
    void timeAlert(tm time);
}

Schedule.cpp

void Schedule::timeAlert(tm time) {
    sleep_until (system_clock::from_time_t (timegm(&time)));
    cout << "It is " << std::asctime(&time);
}

Why is it treating this function like a non-member? It clearly is a member of Schedule…

> Why is it treating this function like a non-member? It clearly is a member of Schedule

main()

is not a member function.
If the function must be non-static, an object of the class type is required.

For example:

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
#include <iostream>
#include <thread>
#include <chrono>
#include <ctime>

struct scheduler {

    void wake_up_and_alert_at( std::time_t time ) const {

        std::this_thread::sleep_until( std::chrono::system_clock::from_time_t(time) ) ;
        std::cout << "alert from " << name << ": it is " << std::ctime( std::addressof(time) );
    }

    std::string name ;
};

int main() {

    const auto now = std::time(nullptr) ;
    std::cout << std::ctime( std::addressof(now) );

    scheduler sch { "scheduler X" } ;
    std::thread t( &scheduler::wake_up_and_alert_at, std::addressof(sch), now+5 ) ;
    t.join() ;
}

OK I set it up like this:

1
2
3
Schedule mySchedule;  
std::thread t(&Schedule::timeAlert, std::addressof(mySchedule), time1);
t.join();

And I got this error:

 In function `std::thread::thread<void (Schedule::*)(tm), Schedule*, tm&>(void (Schedule::*&&)(tm), Schedule*&&, tm&)':
/usr/include/c++/7/thread:122: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

What does this mean?

Last edited on

With the GNU tool chain, the compiler option

-pthread

is required.
For example:

g++ -std=c++17 -O3 -Wall -Wextra -pedantic-errors -pthread my_program.cpp

OK I added it in…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
CXX = g++
CXXFLAGS = -c -g -std=c++11 -Wall -W -Werror -pthread -pedantic
LDFLAGS =

schedule: main.o schedule.o
	$(CXX) $(LDFLAGS) main.o schedule.o -o main

main.o : main.cpp
	$(CXX) $(CXXFLAGS) main.cpp

schedule.o: schedule.cpp schedule.h
	$(CXX) $(CXXFLAGS) schedule.cpp

clean :
	rm -f core $(PROG) *.o

But I’m still getting the same error:

In function `std::thread::thread<void (Schedule::*)(tm), Schedule&, tm&>(void (Schedule::*&&)(tm), Schedule&, tm&)':
/usr/include/c++/7/thread:122: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

I did a make clean first just to be safe, but that didn’t solve it.

Add

-pthread

to the link options too:

LDFLAGS = -pthread

Topic archived. No new replies allowed.

Are you using Qt Creator? If so you should start by adding a new class. Let’s call it Press, then Qt creator will create press.h and press.cpp for your. Press. h will look like this:
@class Press : public QWidget
{
Q_OBJECT
public:
explicit Press(QWidget *parent = 0);

signals:

public slots:

};
@

press.cpp will look like this
@
#include «press.h»

Press::Press(QWidget *parent) :
QWidget(parent)
{
}
@

When you add any private member to your .h file like

@ QPushButton* saveButton;@

You should initialize it in your class constructor’s initializer list. That would give you a .h file that now looks like this

@
#include <QWidget>

class QPushButton;

class Press : public QWidget
{
Q_OBJECT
public:
explicit Press(QWidget *parent = 0);

signals:
    
public slots:
    
private:
    QPushButton* saveButton;

};
@

and a .cpp file that looks like this:

@
#include «press.h»
#include <QPushButton>

Press::Press(QWidget *parent) :
QWidget(parent),
saveButton (new QPushButton(«Save»,this))
{
}
@

Now your saveButton pointer has a legitimate value when the class constructor runs. Of course you have to run the class constructor. So somewhere in main if you want to use the Press class you need the include and a statement that looks like this is you want a solid instance of your object.

@
Press myPress;
@

THEN when you want to use Save in a connect statement you would use a statement like this:

@
QObject::connect(saveButton,SIGNAL(clicked()), &myPress, SLOT(Save()));
@

That line assumes saveButton is a pointer. With savePointer as a solid object main would end up looking something like this

@
Press myPress;
QPushButton saveButton;
QObject::connect(&saveButton,SIGNAL(clicked()), &myPress, SLOT(Save()));
@

While what follows is self-promotion I REALLY think you would benefit from watching my «Introduction to Qt»:http://bit.ly/introqt course on Pluralsight.
Pluralsight is a subscription service. You have the right to a subscription service If you can’t afford a subscription service one will be provided to you!

Just send me an email through the forum and I’ll give you a VIP pass good for unlimited hours (includes offline viewing) that lasts for one week. My first course is four+ hours long. You should be able to watch both it and my class on «Qt Quick»:http://bit.ly/qtquickfun. It should even give you enough time to watch some of the programming classes on C++.

Edit:Fixed memory leaks.

MaxFilippov

1 / 1 / 0

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

Сообщений: 50

1

05.05.2017, 19:25. Показов 15797. Ответов 2

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


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
#include <iostream>
 
 
using namespace std;
 
class fraction
{
    
    fraction(double var_sum)
    { 
        
        
        var_sum=m+n;
        var_sum=m-n;
        var_sum=m/m;
        var_sum=m*n;
        
    }
    
    private:
 
    double m,n;
    public:
    
    double var_sum;
     double setdata(double var_sum );
     fraction() {}
};  
double fraction::setdata(double sum_d)
    {
        
        
        sum_d=var_sum;
        
        return  sum_d;
    }
 
 
int  main()
{
    double a;
    cin>>a;
    fraction work;
    cout<<work.setdata<<endl;//Здесь выдает ошибку
    
         return 0;
     }

Ошибка:invalid use of non-static member function

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

0

Hitoku

1754 / 1346 / 1407

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

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

05.05.2017, 19:40

2

Попробуйте так

C++
44
cout << work.setdata(a) << endl;

Добавлено через 1 минуту
Функция же объявлена с параметром, но вы его не передаёте

1

1 / 1 / 0

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

Сообщений: 50

05.05.2017, 19:43

 [ТС]

3

Спасибо,что-то затупил)

0


Форум программистов Vingrad

Новости ·
Фриланс ·
FAQ

Правила ·
Помощь ·
Рейтинг ·
Избранное ·
Поиск ·
Участники

> Использование this в main.cpp 

:(

Опции темы

evgenyustimenko

Новичок

Профиль
Группа: Участник
Сообщений: 1
Регистрация: 24.9.2010

Репутация: нет
Всего: нет

Всем привет, столкнулся вот с какой проблемой. Код не хочет компилироваться из-за this в файле main.cpp.

Ошибка следующая:
invalid use of ‘this’ in non-member function

Код, где используется:
pthread_create(&inetThread,NULL,inet.Thread(argv),(void*)this);

Google порыл, ни фига путнего не нашел.

БелАмор

Бывалый
*

Профиль
Группа: Участник
Сообщений: 209
Регистрация: 10.6.2010
Где: Россия

Репутация: нет
Всего: 17

this — ключевое слово. Означает указатель на свой объект внутри функции-члена класса (методе).
В функции, не являющейся методом, this не имеет смысла, о чём чистым английским языком и сообщил компилятор.



















Правила форума «C/C++: Для новичков»
JackYF
bsa

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь

  • FAQ раздела лежит здесь!

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa.

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Для новичков | Следующая тема »
Автор Тема: QNetworkAccessManager ошибки  (Прочитано 6961 раз)
build1423

Гость


Здраствуйте. Пишу я небольшую функцию и нужно использовать QNetworkAccessManager. При его обьявлении параметром нужно вписать QObject parent. Если я передаю QCoreApplication как параметр моей функции

C++ (Qt)

void myfunc(QCoreApplication b)
{
   QNetworkAccessManager *myManager = new QNetworkAccessManager(&b);
}

 int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    myfunc(a);
    return 0;
}

То вылетает, что QCoreApplication приватная. Если использовать ключевое слово this

C++ (Qt)

void myfunc()
{
   QNetworkAccessManager *myManager = new QNetworkAccessManager(this);
}

 int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    myfunc();
    return 0;
}

То вылетает error: invalid use of ‘this’ in non-member function.
Если в название добавить класс, с которым будем работать

C++ (Qt)

void QCoreApplication::myfunc()
{
   QNetworkAccessManager *myManager = new QNetworkAccessManager(this);
}

 int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    return 0;
}

то вылетает error: no ‘void QCoreApplication::myfunc()’ member function declared in class ‘QCoreApplication’ и вызвать мою функцию в main нельзя. Так как правильно использовать QNetworkAccessManager?


Записан
kuzulis

Изучи-ка сначала C++ и твой вопрос сам по себе решится.


Записан

ArchLinux x86_64 / Win10 64 bit

build1423

Гость


Изучи-ка сначала C++ и твой вопрос сам по себе решится.

Ну правильно. Вместо того, что бы сказать, которую строчку нужно исправить, и как, потратив на это 5 секунд, Вы мне предлагаете изучить полностью С++. Прочтение  одной книги будет маловато, как по мне. Нужно прочитать миннимум две, по пару раз. Времени на это потратится, предположим, 3 месяца. Задачу, которую мне нужно сделать, сдавать через 2 недели. Так не думаете ли Вы, что совет, даный Вами же не рационален.


Записан
alex312

Хакер
*****
Offline Offline

Сообщений: 606

Просмотр профиля


что совет, даный Вами же не рационален.

Зато бесплатный  Смеющийся


Записан
build1423

Гость


Издеваться над новичком в теме для новичков это конечно дело весёлое и благородное(а главное — бесплатное!), но я всё-же надеюсь на помощь.


Записан
alex312

Хакер
*****
Offline Offline

Сообщений: 606

Просмотр профиля


но я всё-же надеюсь на помощь.

Найтиде кого-то, кто сделает за вас эту лабораторку. Это серьезно, с вашим знанием С++ — это единственный разумный выход для вас.


Записан
build1423

Гость


Вы издеваетесь? Я не поучительств ищу на форуме, а ответ на вопрос. С++ я знаю в достаточной мере для того, что бы написать то, что мне нужно. Но вот немогу я правильно инициализировать обьект класса. В примерах, которых куча, взять хотябы http://qt-project.org/doc/qt-4.8/qnetworkaccessmanager.html написано QNetworkAccessManager *manager = new QNetworkAccessManager(this); Они тоже не знают С++ и им его надо учить? Если не можете помочь, так уж молчите, прошу.


Записан
alex312

Хакер
*****
Offline Offline

Сообщений: 606

Просмотр профиля


Вы издеваетесь? Я не поучительств ищу на форуме, а ответ на вопрос. С++ я знаю в достаточной мере для того, что бы написать то, что мне нужно.

А может это вы издеваетесь? И если вы «знаете» С++, то что вам не понятно в строке

C++ (Qt)

QNetworkAccessManager ( QObject * parent = 0 );

Непонимающий


Записан
build1423

Гость


Что именно должно быть параметром? Только не надо ответов вроде указатель на обьект типа QObject.


Записан
kambala

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

код в первом посте говорит совсем об обратном

чтобы исправить ошибку в первом варианте, параметр функции должен быть не QCoreApplication b, а const QCoreApplication &b


Записан

Изучением C++ вымощена дорога в Qt.

UTF-8 has been around since 1993 and Unicode 2.0 since 1996; if you have created any 8-bit character content since 1996 in anything other than UTF-8, then I hate you. © Matt Gallagher

build1423

Гость


параметр функции должен быть не QCoreApplication b, а const QCoreApplication &b

error: invalid conversion from ‘const QObject*’ to ‘QObject*’ [-fpermissive]


Записан
alex312

Хакер
*****
Offline Offline

Сообщений: 606

Просмотр профиля


error: invalid conversion from ‘const QObject*’ to ‘QObject*’ [-fpermissive]

C++ (Qt)

QNetworkAccessManager *myManager = new QNetworkAccessManager(const_cast<QCoreApplication*>(&b));

Записан
kambala

ну тогда параметр без конст просто


Записан

Изучением C++ вымощена дорога в Qt.

UTF-8 has been around since 1993 and Unicode 2.0 since 1996; if you have created any 8-bit character content since 1996 in anything other than UTF-8, then I hate you. © Matt Gallagher

alex312

Хакер
*****
Offline Offline

Сообщений: 606

Просмотр профиля


ну тогда параметр без конст просто

gcc такого не пропустит


Записан
Bepec

Гость


Та вы заканали, знатоки. Тупо не передавай ничего Улыбающийся

т.е.   QNetworkAccessManager *myManager = new QNetworkAccessManager;

Финита ля комедиа?


Записан

I have a problem – discussed a lot previously, but all solutions I saw doesn’t work here.
What is wrong in this code?

main.cpp:8:19: error: invalid use of ‘this’ in non-member function

#include <QApplication>
#include <QPainter>
#include <math.h>
class QPainter;

int main(int argc, char *argv[]){
  QApplication app(argc,argv);

  QPainter painter(this);
  painter.setPen(QPen(Qt::black,3));

  int n=8;
  for (int i=0;i<n;++i){
    qreal fAngle=2*3.14*i/n;
    qreal x = 50 + cos(fAngle)*40;
    qreal y = 50 + sin(fAngle)*40;
    painter.drawPoint(QPointF(x,y));
  }


  return app.exec();    
}

  • Home
  • Forum
  • Qt
  • Qt Programming
  • invalid use of this in non member function

  1. 19th January 2011, 10:27


    #1

    Default invalid use of this in non member function

    hi i want to do a qt mobile apps which using network access but while compiling my code it shows the following errors.

    i. invalid use of this in non member function
    ii. connect was not declared in this scope

    I have do the following in my code:

    .pro file:

    1. QT += network

    To copy to clipboard, switch view to plain text mode 

    main.cpp file

    1. #include <QtGui/QApplication>

    2. #include "mainwindow.h"

    3. #include <QtNetwork>

    4. int main(int argc, char *argv[])

    5. {

    6. MainWindow w;

    7. QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    8. connect(manager, SIGNAL(finished(QNetworkReply*)),

    9. this, SLOT(replyFinished(QNetworkReply*)));

    10. manager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));

    11. #if defined(Q_WS_S60)

    12. w.showMaximized();

    13. #else

    14. w.show();

    15. #endif

    16. return a.exec();

    17. }

    To copy to clipboard, switch view to plain text mode 

    Is it any problem with my code please help me. Thanks.


  2. 19th January 2011, 10:31


    #2

    Default Re: invalid use of this in non member function

    connect() is a method of QObject and not a standalone function.

    1. QObject::connect(manager, SIGNAL(finished(QNetworkReply*)),

    2. this, SLOT(replyFinished(QNetworkReply*)));

    To copy to clipboard, switch view to plain text mode 

    Last edited by wysota; 19th January 2011 at 10:36.

    Your biological and technological distinctiveness will be added to our own. Resistance is futile.

    Please ask Qt related questions on the forum and not using private messages or visitor messages.


  3. The following user says thank you to wysota for this useful post:

    dineshkumar (19th January 2011)


  4. 19th January 2011, 10:37


    #3

    Default Re: invalid use of this in non member function

    hi thanks,
    But it again shows the following error:

    invalid use of this in non member function


  5. 19th January 2011, 10:53


    #4

    Default Re: invalid use of this in non member function

    There is no «this» in main().

    Your biological and technological distinctiveness will be added to our own. Resistance is futile.

    Please ask Qt related questions on the forum and not using private messages or visitor messages.


  6. The following user says thank you to wysota for this useful post:

    dineshkumar (19th January 2011)


  7. 19th January 2011, 10:56


    #5

    Default Re: invalid use of this in non member function

    1. replyFinished(QNetworkReply*)

    To copy to clipboard, switch view to plain text mode 

    where is this function defined? you need that class object to be passed in connect instead of «this», the same as you pass «manager».


  8. The following user says thank you to nish for this useful post:

    dineshkumar (19th January 2011)


  9. 19th January 2011, 13:38


    #6

    Default Re: invalid use of this in non member function

    It is probably easier if you move your code to the MainWindow instead:

    main.cpp:

    1. // main.cpp

    2. #include <QtGui/QApplication>

    3. #include "mainwindow.h"

    4. int main(int argc, char *argv[])

    5. {

    6. MainWindow w;

    7. #if defined(Q_WS_S60)

    8. w.showMaximized();

    9. #else

    10. w.show();

    11. #endif

    12. return a.exec();

    13. }

    To copy to clipboard, switch view to plain text mode 

    mainwindow.h:

    1. // mainwindow.h

    2. #ifndef MAINWINDOW_H

    3. #define MAINWINDOW_H

    4. #include <QtGui/QMainWindow>

    5. class QNetworkReply;

    6. {

    7. Q_OBJECT

    8. public:

    9. explicit MainWindow(QWidget *parent = 0);

    10. ~MainWindow();

    11. protected slots:

    12. void replyFinished(QNetworkReply *reply);

    13. };

    14. #endif // MAINWINDOW_H

    To copy to clipboard, switch view to plain text mode 

    mainwindow.cpp

    1. // mainwindow.cpp

    2. #include <QtNetwork/QtNetwork>

    3. #include <QtNetwork/QNetworkReply>

    4. #include "mainwindow.h"

    5. #include <QDebug>

    6. {

    7. QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    8. connect(manager, SIGNAL(finished(QNetworkReply*)),

    9. this, SLOT(replyFinished(QNetworkReply*)));

    10. manager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));

    11. }

    12. MainWindow::~MainWindow()

    13. {

    14. }

    15. void MainWindow::replyFinished(QNetworkReply *reply)

    16. {

    17. qDebug() << "ok!";

    18. }

    To copy to clipboard, switch view to plain text mode 


  10. The following 2 users say thank you to helloworld for this useful post:

    dineshkumar (20th January 2011), tylor2000 (13th December 2015)


  11. 20th January 2011, 05:19


    #7

    Default Re: invalid use of this in non member function

    Thankyou friend its works..


  12. 13th December 2015, 19:37


    #8

    Post Re: invalid use of this in non member function

    Thank you helloworld, this helped me out a lot. You will probably never see this but just wanted to thank you for the code example. It’s still helping people out after all these years.


Similar Threads

  1. Replies: 0

    Last Post: 24th October 2010, 19:09

  2. Replies: 3

    Last Post: 8th July 2010, 13:12

  3. Replies: 4

    Last Post: 29th July 2009, 15:23

  4. Replies: 22

    Last Post: 8th October 2008, 13:54

  5. Replies: 4

    Last Post: 19th June 2006, 15:21

Bookmarks

Bookmarks


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.

  • Ошибка invalid use of incomplete type class ui mainwindow
  • Ошибка invalid use of incomplete type class qdebug
  • Ошибка invalid stfs package horizon что делать
  • Ошибка invalid start mode archive offset что делать
  • Ошибка invalid signature detected check secure boot policy in setup как исправить