【发布时间】:2016-12-02 12:03:27
【问题描述】:
#include <iostream>
#include<cstdio>
#include<typeinfo>
using std::cout;
using std::endl;
class foo;
class bar
{
public:
bar()
{
}
bar(void (*getNextValue)(void)):memberFunctionPointer(getNextValue)
{
}
void calltoderivedslass()
{
// *memberFunctionPointer();
((bar*)this)->bar::memberFunctionPointer;
}
void (foo::*memberFunctionPointer)();
};
class foo : public bar
{
public:
foo( ):bar(static_cast<foo::*memberFunctionPointer>(&foo::hello))
{
}
void hello()
{
printf("Hello \n\n");
}
};
void byebye()
{
cout << "bye" << endl;
}
int main()
{
foo testfoo;
//((testfoo).*(testfoo.memberFunctionPointer))();
return 0;
}
错误:
classname.cpp: In constructor "bar::bar(void (*)())":
classname.cpp:15:68: error: cannot convert "void (*)()" to "void (foo::*)()" in initialization
classname.cpp: In constructor "foo::foo()":
classname.cpp:29:25: error: expected type-specifier
classname.cpp:29:25: error: expected ">"
classname.cpp:29:25: error: expected "("
classname.cpp:29:30: error: expected unqualified-id before "*" token
classname.cpp:31:2: error: expected "{" at end of input
期望:
我要初始化基类函数指针,初始化它指向派生类成员函数。我想在创建派生类的对象时初始化它。从基类我想使用获取的函数指针调用派生类函数。
提前感谢大家。
【问题讨论】:
-
如果您正确使用 OOP,则无需使用函数指针...考虑一下必须维护您的代码的程序员..
-
是的,需要使用函数指针。当数据库读取发生错误时,必须调用回调,所以我需要函数指针,不要给代码维护带来困难。谢谢:)
标签: c++ class constructor callback function-pointers