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
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, 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
![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
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.
- Forum
- Beginners
- Error’s on overloaded operators = and +
Error’s on overloaded operators = and +
Hi there,
I’m trying to build a class that holds 2d coordinates, and as far as i can see, i’ve done everything i ought to in order to define the class. When i compile the code though, it gives me a few different error methods.
Every time i use «this» i get an error message:
error: invalid use of 'this' in non-member function
and for the ‘=’ operator, i get two other error messages:
error: 'two_vector& operator=(two_vector&)' must be a nonstatic member function error: 'two_vector& operator=(two_vector&)' must take exactly two arguments
I’ve searched around, but all i can find on the topic has proved hard to relate back to my code. More annoyingly, i tried defining the methods inside the class definition (replacing the prototypes) and in that case, the code compiles, and functions fine. This is my code:
|
|
I’d be greatly if anyone can help. Really sorry if this is a blindingly obvious mistake on my part..
Many thanks
You got your qualifiers a bit mixed up:
|
|
Ah..*bows head*
Well i guess on the bright side it was easy to resolve.. Thanks a lot Galik!
also note you should be const correct:
|
|
Disch,
I made the changes you suggest, but it now rather sadistically gives me six more errors:
error: passing 'const two_vector' as 'this' argument of 'int two_vector::get_x()' discards qualifiers error: passing 'const two_vector' as 'this' argument of 'int two_vector::get_y()' discards qualifiers
So i fear you might have increased your workload but can you help me out with this? I tried adding const to quantify get_x and get_y, but that made things worse.. In order to see if it was all get_x and get_y’s I redefined the method to be:
|
|
Which only showed that it really is every get_x and get_y.. Im nervous this is once again something slightly obvious.. i dont suppose you have a newbie point system at all?
Also, for the + operator, whats the purpose of the const at the end of the prototype?
Thanks a lot
well for starters… do you really need get/set fucntions for x and y or are those useless getters/setters?
My guess is they’re useless, so I would get rid of them and just make x and y public. There’s nothing wrong with public members where appropriate. Useless getters/setters are a waste of time and energy and make the interface weird.
But if they’re useful, the solution is to make get_x and get_y const:
|
|
Also, for the + operator, whats the purpose of the const at the end of the prototype?
It makes the function const.
const functions «promise» not to change the state of the object. Therefore they can be called by const objects.
non-const functions might change the state of the object, therefore they can only be called by nonconst objects.
|
|
Similarly, const functions can only call other const functions. This is the error you were getting. Your + operator (const) was trying to call get_x (nonconst). Since get_x might change the state of the object, this breaks the «promise», and therefore the compiler barks at you.
EDIT:
I just realized you posted the entire class above!
Yes, get_x/get_y/set_x/set_y are useless getters/setters. Get rid of them. x and y should be public for this class.
Last edited on
Right then, i’ll set about removing the setters and getters. What situations are setters and getters useful?
To clarify though, to declare a function as const, the const goes after the name of the function, but before the {}’s ? Why is it different to when a const variable is declared, or can this also be done after the variable name?
Cheers
To clarify though, to declare a function as const, the const goes after the name of the function, but before the {}’s ? Why is it different to when a const variable is declared, or can this also be done after the variable name?
You are looking for some consistent naming convention is it ? Unfortunately, C++ works in a myriad ways.
int var const = 0; // compile error
const int var = 0; // compile ok
This is something Bjarne Stroustrop C++ creator should have know when he create the language!
grenoble12 wrote: |
---|
To clarify though, to declare a function as const, the const goes after the name of the function, but before the {}’s ? Why is it different to when a const variable is declared, or can this also be done after the variable name? |
When you access a variable you tell the compiler if the returned value is const or not:
|
|
When you access a function you tell the compiler if the returned value is const or not:
|
|
So we need a different way to tell the compiler that the function itself will not modify its object. So we put const after the function parameters to signify this:
|
|
What situations are setters and getters useful?
When the class needs to enforce some invariant. For example, if your two_vector class only allowed
x and y to be even numbers, you could:
|
|
Or, if you need to provide synchronization (ie, the invariant of the class is thread safety), then a setter and
getter would acquire the necessary locks, perform the read or write operation, and free the locks.
Otherwise, setters and getters are simply red tape with no real benefit. Setters and getters generally break
encapsulation since they imply that the user of the object knows better what the values should be than the
object itself; the object is simply a container of those values.
EDIT: Note that if this is for homework, your professor is probably looking for a «purer» solution which would
mean writing the useless setters and getters anyway, even though professionally I would eschew them in
favor of direct access.
Last edited on
Thanks peeps, Galik that makes a lot of sense and jsmith this isnt for homework, ive just found myself with some free time and decided to remind myself of C++. I remember my teachers telling us to include them on some pretty similar class to this one, which is why i though they were necessary or at least safer to include..
Thanks again for all the advice.
Topic archived. No new replies allowed.
Вы просто пытались скопировать какой-то код, не понимая, что происходит.
Похоже, вы видели такой код:
#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/
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.
|
Автор | Тема: QNetworkAccessManager ошибки (Прочитано 7022 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
Форум программистов Vingrad
Новости ·
Фриланс ·
FAQ
Правила ·
Помощь ·
Рейтинг ·
Избранное ·
Поиск ·
Участники
Модераторы: bsa |
Поиск: |
|
Опции темы |
evgenyustimenko |
|
||
Новичок Профиль Репутация: нет
|
Всем привет, столкнулся вот с какой проблемой. Код не хочет компилироваться из-за this в файле main.cpp. Ошибка следующая: Код, где используется: Google порыл, ни фига путнего не нашел. |
||
|
|||
БелАмор |
|
||
Бывалый Профиль
Репутация: нет
|
this — ключевое слово. Означает указатель на свой объект внутри функции-члена класса (методе). |
||
|
|||
|
Правила форума «C/C++: Для новичков» | |
|
Запрещается! 1. Публиковать ссылки на вскрытые компоненты 2. Обсуждать взлом компонентов и делиться вскрытыми компонентами
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa. |
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | C/C++: Для новичков | Следующая тема » |