Error invalid use of this in non member function

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 f...

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

    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, 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.

  • 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:

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
class two_vector{
	int x, y;
public: 
	int get_x() { return x; }
	int get_y() { return y; }
	void set_x(int a) { x = a;}
	void set_y(int a) { y = a;}
	two_vector();
	two_vector(int, int);
	two_vector operator+ (two_vector&);
	two_vector& operator= (two_vector&);
};

two_vector::two_vector() {
	x=0;
	y=0;
}

two_vector::two_vector(int a, int b) {
	x = a;
	y = b;
}

two_vector::two_vector operator+ (two_vector& rhs){
	int a = rhs.get_x() + this->get_x();
	int b = rhs.get_y() + this->get_y();
	return two_vector(a,b);
}

two_vector::two_vector& operator= (two_vector& rhs){
	if (&rhs != this){
		this->set_x(rhs.get_x());
		this-> set_y(rhs.get_y());
	}
	return *this;	
}

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
two_vector two_vector::operator+ (two_vector& rhs){
	int a = rhs.get_x() + this->get_x();
	int b = rhs.get_y() + this->get_y();
	return two_vector(a,b);
}

two_vector& two_vector::operator= (two_vector& rhs){
	if (&rhs != this){
		this->set_x(rhs.get_x());
		this-> set_y(rhs.get_y());
	}
	return *this;
}

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:

1
2
3
4
5
//  two_vector operator+ (two_vector&);  //  bad
two_vector operator + (const two_vector&) const; // good

//  two_vector& operator= (two_vector&);  // bad
two_vector& operator = (const two_vector&); // good 

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:

1
2
3
4
5
6
7
two_vector two_vector::operator+ (const two_vector& rhs) const{
	int a = rhs.get_x();
	int b = this->get_x();
	int c = rhs.get_y();
	int d = this->get_y();
	return two_vector(a+b,c+d);
}

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:

1
2
3
4
//int two_vector::get_x();  // bad
int two_vector::get_x() const;  // good

// same for get_y() 

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class example
{
public:
  void nonconst() { }  // a non-const function
  void yesconst() const { }  // a const function
};

int main()
{
  example a;
  a.nonconst();  // OK
  a.yesconst();  // OK

  const example b;
  b.nonconst();  // ERROR, const object calling nonconst function
  b.yesconst();  // OK
}

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! :P

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:

 
const int value; // returns a const 

When you access a function you tell the compiler if the returned value is const or not:

 
const int object.function(); returns a const, non const function

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:

 
const int object.function() const; returns a const, const function

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:

1
2
3
4
5
6
  bool set_x( int new_x ) {
      if( new_x % 2 )
          return false;
      x = new_x;
      return true;
  }

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 раз)
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;

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


Записан


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

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

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

Модераторы: bsa

Поиск:

Ответ в темуСоздание новой темы
Создание опроса
> Использование this в main.cpp 

:(

   

Опции темы

evgenyustimenko
Дата 24.9.2010, 21:30 (ссылка)
   | (голосов:2)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Новичок

Профиль
Группа: Участник
Сообщений: 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 порыл, ни фига путнего не нашел.

PM MAIL   Вверх
БелАмор
Дата 24.9.2010, 21:43 (ссылка)
|    (голосов:1)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Бывалый
*

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

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

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

PM   Вверх



















Ответ в темуСоздание новой темы
Создание опроса
Правила форума «C/C++: Для новичков»
JackYF
bsa

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

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

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

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

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

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

 

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

Понравилась статья? Поделить с друзьями:
  • Error invalid use of incomplete type
  • Error invalid url unable to find install package
  • Error invalid type argument of unary have int
  • Error invalid type argument of unary have float
  • Error invalid transaction termination