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.
|
|
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:
|
|
OK I set it up like this:
|
|
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…
|
|
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/
- Forum
- Qt
- Qt Programming
- invalid use of this in non member function
-
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 scopeI have do the following in my code:
.pro file:
QT += network
To copy to clipboard, switch view to plain text mode
main.cpp file
#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QtNetwork>
int main(int argc, char *argv[])
{
MainWindow w;
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));
#if defined(Q_WS_S60)
w.showMaximized();
#else
w.show();
#endif
return a.exec();
}
To copy to clipboard, switch view to plain text mode
Is it any problem with my code please help me. Thanks.
-
19th January 2011, 11:31
#2
Re: invalid use of this in non member function
connect() is a method of QObject and not a standalone function.
QObject::connect(manager, SIGNAL(finished(QNetworkReply*)),
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.
-
The following user says thank you to wysota for this useful post:
dineshkumar (19th January 2011)
-
19th January 2011, 11:37
#3
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
-
19th January 2011, 11:53
#4
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.
-
The following user says thank you to wysota for this useful post:
dineshkumar (19th January 2011)
-
19th January 2011, 11:56
#5
Re: invalid use of this in non member function
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».
-
The following user says thank you to nish for this useful post:
dineshkumar (19th January 2011)
-
19th January 2011, 14:38
#6
Re: invalid use of this in non member function
It is probably easier if you move your code to the MainWindow instead:
main.cpp:
// main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
MainWindow w;
#if defined(Q_WS_S60)
w.showMaximized();
#else
w.show();
#endif
return a.exec();
}
To copy to clipboard, switch view to plain text mode
mainwindow.h:
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui/QMainWindow>
class QNetworkReply;
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected slots:
void replyFinished(QNetworkReply *reply);
};
#endif // MAINWINDOW_H
To copy to clipboard, switch view to plain text mode
mainwindow.cpp
// mainwindow.cpp
#include <QtNetwork/QtNetwork>
#include <QtNetwork/QNetworkReply>
#include "mainwindow.h"
#include <QDebug>
{
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));
}
MainWindow::~MainWindow()
{
}
void MainWindow::replyFinished(QNetworkReply *reply)
{
qDebug() << "ok!";
}
To copy to clipboard, switch view to plain text mode
-
The following 2 users say thank you to helloworld for this useful post:
dineshkumar (20th January 2011), tylor2000 (13th December 2015)
-
20th January 2011, 06:19
#7
Re: invalid use of this in non member function
Thankyou friend its works..
-
13th December 2015, 20:37
#8
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
-
Replies: 0
Last Post: 24th October 2010, 20:09
-
Replies: 3
Last Post: 8th July 2010, 14:12
-
Replies: 4
Last Post: 29th July 2009, 16:23
-
Replies: 22
Last Post: 8th October 2008, 14:54
-
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.
|
|
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:
|
|
OK I set it up like this:
|
|
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…
|
|
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 Метки нет (Все метки)
Ошибка:invalid use of non-static member function
__________________ 0 |
Hitoku 1754 / 1346 / 1407 Регистрация: 28.10.2016 Сообщений: 4,267 |
||||
05.05.2017, 19:40 |
2 |
|||
Попробуйте так
Добавлено через 1 минуту 1 |
1 / 1 / 0 Регистрация: 26.03.2017 Сообщений: 50 |
|
05.05.2017, 19:43 [ТС] |
3 |
Спасибо,что-то затупил) 0 |
Форум программистов Vingrad
Новости ·
Фриланс ·
FAQ
Правила ·
Помощь ·
Рейтинг ·
Избранное ·
Поиск ·
Участники
Использование this в main.cpp |
Опции темы |
evgenyustimenko | |
Новичок Профиль Репутация: нет |
Всем привет, столкнулся вот с какой проблемой. Код не хочет компилироваться из-за this в файле main.cpp. Ошибка следующая: Код, где используется: Google порыл, ни фига путнего не нашел. |
БелАмор | |
Бывалый Профиль
Репутация: нет |
this — ключевое слово. Означает указатель на свой объект внутри функции-члена класса (методе). |
Правила форума «C/C++: Для новичков» | |
|
Запрещается! 1. Публиковать ссылки на вскрытые компоненты 2. Обсуждать взлом компонентов и делиться вскрытыми компонентами
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa. |
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | C/C++: Для новичков | Следующая тема » |
Автор | Тема: QNetworkAccessManager ошибки (Прочитано 6961 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
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();
}
- Forum
- Qt
- Qt Programming
- invalid use of this in non member function
-
19th January 2011, 10:27
#1
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 scopeI have do the following in my code:
.pro file:
QT += network
To copy to clipboard, switch view to plain text mode
main.cpp file
#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QtNetwork>
int main(int argc, char *argv[])
{
MainWindow w;
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));
#if defined(Q_WS_S60)
w.showMaximized();
#else
w.show();
#endif
return a.exec();
}
To copy to clipboard, switch view to plain text mode
Is it any problem with my code please help me. Thanks.
-
19th January 2011, 10:31
#2
Re: invalid use of this in non member function
connect() is a method of QObject and not a standalone function.
QObject::connect(manager, SIGNAL(finished(QNetworkReply*)),
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.
-
The following user says thank you to wysota for this useful post:
dineshkumar (19th January 2011)
-
19th January 2011, 10:37
#3
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
-
19th January 2011, 10:53
#4
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.
-
The following user says thank you to wysota for this useful post:
dineshkumar (19th January 2011)
-
19th January 2011, 10:56
#5
Re: invalid use of this in non member function
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».
-
The following user says thank you to nish for this useful post:
dineshkumar (19th January 2011)
-
19th January 2011, 13:38
#6
Re: invalid use of this in non member function
It is probably easier if you move your code to the MainWindow instead:
main.cpp:
// main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
MainWindow w;
#if defined(Q_WS_S60)
w.showMaximized();
#else
w.show();
#endif
return a.exec();
}
To copy to clipboard, switch view to plain text mode
mainwindow.h:
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui/QMainWindow>
class QNetworkReply;
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected slots:
void replyFinished(QNetworkReply *reply);
};
#endif // MAINWINDOW_H
To copy to clipboard, switch view to plain text mode
mainwindow.cpp
// mainwindow.cpp
#include <QtNetwork/QtNetwork>
#include <QtNetwork/QNetworkReply>
#include "mainwindow.h"
#include <QDebug>
{
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));
}
MainWindow::~MainWindow()
{
}
void MainWindow::replyFinished(QNetworkReply *reply)
{
qDebug() << "ok!";
}
To copy to clipboard, switch view to plain text mode
-
The following 2 users say thank you to helloworld for this useful post:
dineshkumar (20th January 2011), tylor2000 (13th December 2015)
-
20th January 2011, 05:19
#7
Re: invalid use of this in non member function
Thankyou friend its works..
-
13th December 2015, 19:37
#8
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
-
Replies: 0
Last Post: 24th October 2010, 19:09
-
Replies: 3
Last Post: 8th July 2010, 13:12
-
Replies: 4
Last Post: 29th July 2009, 15:23
-
Replies: 22
Last Post: 8th October 2008, 13:54
-
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.