我在使用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;
}
编译器在 testFoo.myBar.funcP = &testFoo.hello;
报错:
ISO C++ 禁止使用绑定的成员函数的地址来形成成员函数指针。请使用 '&foo::hello'
在赋值中无法将 'void (foo::)()' 转换为 'void ()()'
我尝试了这样写:
class bar
{
public:
void (*foo::funcP)();
};
但现在编译器又添加了一个错误信息:
'foo'未被声明
有办法解决这个问题吗?
提前感谢您的建议。
bar
添加一个默认构造函数,将两个指针都设置为0
。您可以设置类,使其始终仅设置一个成员(即将一个成员设置为0
),然后添加一个operator()
函数来调用设置的成员。虽然最终会比这更复杂。 - Chris Lutz