У меня есть проблема с использованием указателя для функционирования в C++. Вот мой пример:
#include <iostream>
using namespace std;
class bar
{
public:
void (*funcP)();
};
class foo
{
public:
bar myBar;
void hello(){cout << "hello" << endl;};
};
void byebye()
{
cout << "bye" << endl;
}
int main()
{
foo testFoo;
testFoo.myBar.funcP = &byebye; //OK
testFoo.myBar.funcP = &testFoo.hello; //ERROR
return 0;
}
Compilator возвращает ошибку в testFoo.myBar.funcP = &testFoo.hello;
:
C++ ISO запрещает взятию адреса связанной функции членства формировать указатель на функцию членства. Скажите '&foo:: привет'
не может преобразовать 'пусто (нечто::) ()' для 'освобождения () ()' в присвоении
Таким образом, я попробовал его как это:
class bar
{
public:
void (*foo::funcP)();
};
Но теперь compilator добавляет еще один:
'нечто' не было объявлено
Существует ли путь, заставляют его работать?
Заранее спасибо за предложения
Принимая все предложения вместе, ваше окончательное решение будет выглядеть так:
#include <iostream>
using std::cout;
usind std::endl;
class foo; // tell the compiler there's a foo out there.
class bar
{
public:
// If you want to store a pointer to each type of function you'll
// need two different pointers here:
void (*freeFunctionPointer)();
void (foo::*memberFunctionPointer)();
};
class foo
{
public:
bar myBar;
void hello(){ cout << "hello" << endl; }
};
void byebye()
{
cout << "bye" << endl;
}
int main()
{
foo testFoo;
testFoo.myBar.freeFunctionPointer = &byebye;
testFoo.myBar.memberFunctionPointer = &foo::hello;
((testFoo).*(testFoo.myBar.memberFunctionPointer))(); // calls foo::hello()
testFoo.myBar.freeFunctionPointer(); // calls byebye()
return 0;
}
В C++ FAQ Lite есть некоторые рекомендации по упрощению синтаксиса.
Взяв идею Криса, можно получить что-то вроде этого:
#include <iostream>
using std::cout; using std::endl;
class foo;
typedef void (*FreeFn)();
typedef void (foo::*MemberFn)();
class bar
{
public:
bar() : freeFn(NULL), memberFn(NULL) {}
void operator()(foo* other)
{
if (freeFn != NULL) { freeFn(); }
else if (memberFn != NULL) { ((other)->*(memberFn))(); }
else { cout << "No function attached!" << endl; }
}
void setFreeFn(FreeFn value) { freeFn = value; memberFn = NULL; }
void setMemberFn(MemberFn value) { memberFn = value; freeFn = NULL; }
private:
FreeFn freeFn;
MemberFn memberFn;
};
class foo
{
public:
bar myBar;
void hello() { cout << "foo::hello()" << endl; }
void operator()() { myBar(this); }
};
void bye() { cout << "bye()" << endl; }
int main()
{
foo testFoo;
testFoo();
testFoo.myBar.setMemberFn(&foo::hello);
testFoo();
testFoo.myBar.setFreeFn(&bye);
testFoo();
return 0;
}
Как говорится в ошибке, методы принадлежат классу, а не отдельным экземплярам. По этой причине указатели на бесплатные функции и указатели на нестатические методы - это совершенно разные вещи. Вам также понадобится экземпляр для вызова метода.
//declaring and taking the address of a foo's method
void (foo::*method)() = &foo::hello; //as the compiler nicely suggests
//calling a function through pointer
free_func();
//calling a method through pointer
foo instance;
(instance.*method)();
Вы можете использовать такие библиотеки, как Boost.Bind и Boost.Function (я думаю, также в std :: tr1), чтобы абстрагироваться от разницы, а также привязать экземпляр к методу :
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
using namespace std;
class foo
{
public:
void hello(){cout << "hello" << endl;};
};
void byebye()
{
cout << "bye" << endl;
}
int main()
{
foo testFoo;
boost::function<void()> helloFunc(boost::bind(&foo::hello, testFoo));
boost::function<void()> byeFunc(byebye);
helloFunc();
byeFunc();
return 0;
}
Чтобы ваш второй вариант работал, объявите foo, чтобы компилятор знал, что это класс.
Также обратите внимание, что синтаксис указателя на функцию неверен. *
идет непосредственно перед именем переменной:
class foo;
class bar
{
public:
void (foo::*funcP)();
};