Меню

Ошибка reference to non static member function must be called

I’m using C++ (not C++11). I need to make a pointer to a function inside a class. I try to do following:

void MyClass::buttonClickedEvent( int buttonId ) {
    // I need to have an access to all members of MyClass's class
}

void MyClass::setEvent() {

    void ( *func ) ( int ); 
    func = buttonClickedEvent; // <-- Reference to non static member function must be called

}

setEvent();

But there’s an error: «Reference to non static member function must be called». What should I do to make a pointer to a member of MyClass?

imreal's user avatar

imreal

10.1k2 gold badges32 silver badges47 bronze badges

asked Oct 13, 2014 at 1:04

JavaRunner's user avatar

2

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

answered Oct 13, 2014 at 1:34

imreal's user avatar

imrealimreal

10.1k2 gold badges32 silver badges47 bronze badges

1

you only need to add parentheses after the function call and pass arguments if needed

answered yesterday

téma el bouaazzaoui's user avatar

  • Forum
  • Beginners
  • reference to non static member function?

reference to non static member function?

I’m testing out classes, and I’m confused on how to get past the error:
«reference to non-static member function must be called; did you mean to call it with no arguments?»

Dog.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef DOG_H_INCLUDED
#define DOG_H_INCLUDED
#include <iostream>

using namespace std;

class Dog
{
    public:
    typedef std::size_t size_type;
    static const size_type CAPACITY = 200;
    Dog() : used(0) {}
    string GetData(){return data[used];}

    void insert(const string entry);
    private:
        string data[CAPACITY];
        size_type used;

};


#endif // DOG_H_INCLUDED 

Dog.cpp

1
2
3
4
5
6
7
8
9
10
#include "Dog.h"



void Dog::insert(const string entry) {

    data[used] = entry;
    ++used;

}

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "Dog.h"

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    Dog dog;
    dog.insert("pomeranian");
    cout << dog.GetData;
    return 0;
}

Tried «static void insert …» already?

Try posting the ENTIRE error message you get.

@FurryGuy

main.cpp|11|error: reference to non-static member function must be called; did you mean to call it with no arguments?|

In main.cpp line 11 should be cout << dog.GetData();

No, the ENTIRE error message your compiler is showing.

something like this:

1>6-4_AmbiguousStatements.cpp
1>6-4_AmbiguousStatements.cpp(18): error C2065: 'cout': undeclared identifier

is much more helpful to figuring out what is wrong than what you post.

cout << dog.GetData; should be cout << dog.GetData();

GetData() is a class member function, not a class variable.

Topic archived. No new replies allowed.

yaoman

0 / 0 / 0

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

Сообщений: 11

1

24.03.2015, 17:10. Показов 7081. Ответов 8

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


Здравствуйте. Помогите, пожалуйста, с проблемой : не могу вызвать метод из QMap.

mainwindiw.h:

C++ (Qt)
1
2
3
4
5
6
7
8
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
 
    void setText();
}

mainwindow.cpp:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
void MainWindow::setText() {
    ui->plainTextEdit->appendPlainText("Hello world!");
}
 
void MainWindow::on_pushButton_3_clicked()
{
    QMap <QString, void(*)()> mFunctions;
    mFunctions["setText"] = setText;
    mFunctions["setText"]();
}

Ошибки :

mainwindow.cpp:327: ошибка: reference to non-static member function must be called; did you mean to call it with no arguments?
mFunctions[«setText»] = setText;
^~~~~~~
()
mainwindow.cpp:327: ошибка: assigning to ‘void (*)()’ from incompatible type ‘void’
mFunctions[«setText»] = setText;
^ ~~~~~~~

Пытался заменить void(*)() множеством способов, но все равно выводит ошибки.
Расскажите, пожалуйста, работающий метод вызова функции по тексту в QT. Спасибо.

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



0



dzrkot

zzzZZZ…

527 / 358 / 94

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

Сообщений: 2,041

24.03.2015, 17:57

2

вот так будет работать, проблема будет если foo будет являться методом класса. Т.е. можно по идее просто сделать friend функции

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
void foo()
    {
    qDebug()<<"foo";
    }
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
QMap <QString, void(*)()> mFunctions;
mFunctions["setText"] = foo;
mFunctions["setText"]();
}

ну или вот так, но как вызвать функция я не знаю сам

C++ (Qt)
1
2
3
4
5
6
7
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
QMap <QString, void(Widget::*)()> mFunctions;
mFunctions["setText"] = foo;
mFunctions["setText"]();
}



0



0 / 0 / 0

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

Сообщений: 11

24.03.2015, 18:08

 [ТС]

3

К сожалению ваш способ не работает.



0



Croessmah

Don’t worry, be happy

17779 / 10543 / 2035

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

Сообщений: 26,513

Записей в блоге: 1

24.03.2015, 18:28

4

C++
1
2
3
4
QMap < int , std::function<void()> > mFunctions ;
 
mFunctions["setText"] = std::bind (&MainWindow::setText , *this) ;
mFunctions["setText"]();



0



0 / 0 / 0

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

Сообщений: 11

24.03.2015, 18:48

 [ТС]

5

В ключе QMap необходимо QString, а не int.
на bind выдает ошибку.
Попытался вызвать иные функции, предложенные IDE с bind. Так же ошибки.
Предложите, пожалуйста, иной работающий способ на QT.



0



MakeEasy

41 / 41 / 26

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

Сообщений: 151

24.03.2015, 19:21

6

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

ну или вот так, но как вызвать функция я не знаю сам

Вот так :

C++
1
2
3
4
5
    MainWindow mainWindow1;
    (mainWindow1.*(mFunctions["setText"]))();
    
    MainWindow *mainWindow2;
    (mainWindow2->*(mFunctions["setText"]))();



1



0 / 0 / 0

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

Сообщений: 11

24.03.2015, 19:29

 [ТС]

7

Ошбики(



0



MakeEasy

41 / 41 / 26

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

Сообщений: 151

24.03.2015, 19:34

8

Лучший ответ Сообщение было отмечено yaoman как решение

Решение

Вот так ошибка?

C++
1
2
3
4
5
6
void MainWindow::on_pushButton_3_clicked()
{
    QMap <QString, void(MainWindow::*)()> mFunctions;
    mFunctions["setText"] = &MainWindow::setText;
    (this->*(mFunctions["setText"]))();
}



2



0 / 0 / 0

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

Сообщений: 11

24.03.2015, 20:45

 [ТС]

9

Спасибо огромное!



0



[Ubuntu 13.10, Hydro Desktop-Full from source, C++]

I am having difficulty setting up callback functions for my ROS Topic subscribers, and would appreciate help.

Since all my Topics use the std_msgs::String type, I’ve defined the class shown below with a generic callback function and an instance variable which identifies the specific Topic.

class myCallback {

        const char * eventtype;

public:

        myCallback(const char * eventType) : eventtype(eventType) {}

        void generic_callback(const std_msgs::String::ConstPtr& msg) {
            std::cerr << this->eventtype << " heard: " << msg->data.c_str() << std::endl;
        }

};

For the ROS functionality in my project, I’ve created a separate class gwrbclass.cpp & gwrbclass.h, which include the myCallback class. In the header file, I define myCallback *callbackList[NUM_EVENT_TYPES] as a private variable. In the implementation, I instantiate the required myCallback objects for each entry in the callbackList and try to bind it to the node’s subscriber object as shown below:

for (int j=0; j<NUM_EVENT_TYPES; j++) {
    callbackList[j] = new myCallback(eventName);
    subList[j] = (sNode[j])->subscribe(eventName, 1000, callbackList[j]->generic_callback);  << ERROR OCCURRING HERE
}

I’m getting an error stating : reference to non-static member function must be called , and as far as I can see, the method I’m calling is not static and therefore should work.
If I use subList[j] = (sNode[j])->subscribe(...., &callbackList[j]->generic_callback); the error becomes : cannot create a non-constant pointer to member function.

I’m confused as to why I’m getting this error (which I believe has something to do with std::bind, function typedef, wrapper functions, etc), and would appreciate some help as I can’t figure out the syntax.

In c++ class if we want to call any function then we can call it by creating object. But if function is static, then we can call by ClassName::FunctionName. If non-static function we are call by class::function then it will give error of c++ a nonstatic member reference must be relative to a specific object.

c++ a nonstatic member reference must be relative to a specific object
call static and non-static member function
#include <iostream>
using namespace std;

class A {
public:
	static void Print();
	void Show();
};

void A::Print() {
	cout << "Print" << endl;
}

void A::Show() {
	cout << "Show" << endl;
}

int main() {
	// Static call by ClassName::Func()
	A::Print();

	// error C2352: 'A::Show': illegal call of non-static member function
	A::Show();

	// Non Static call by Obj
	A obj;
	obj.Show();

	return 0;
}

How to Solve this Error ?

  1. You can create Show() function as static function and then call it by class name and scope resolution(::)
  2. You can create class object and then call function by objectName.Function()

Why Static function require to call using scope resolution(::) ?

For static function we need to call function by ClassName::Function, because static function is not attached to particular object. So they does not contain this pointer (*this). Static member functions can directly access to any of other static members variables or functions , but it can not access other non-static members. This is because all non-static functions are attached with object of class so we will require to call it using object.Func.

Conclusion:

Whenever we are getting c++ a nonstatic member reference must be relative to a specific object error in our program we need to use class object to call it or we can make particular function as static, everything is depend on requirement of our code and project.

Reader Interactions

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка r0120 форд фьюжн
  • Ошибка reference by pointer windows 10