【发布时间】:2017-10-29 11:40:51
【问题描述】:
您好,这是我在 C++ 中传递函数指针的第一次体验。 所以这是我的代码:-
#include <iostream>
using namespace std;
// Two simple functions
class student
{
public:
void fun1() { printf("Fun1\n"); }
void fun2() { printf("Fun2\n"); }
// A function that receives a simple function
// as parameter and calls the function
void wrapper(void (*fun)())
{
fun();
}
};
int main()
{ student s;
s.wrapper(s.fun1());
s.wrapper(s.fun2());
return 0;
}
最初在包装函数中我只传递了 fun1 和 fun2。我得到了一个错误
try.cpp:22:15: error: ‘fun1’ was not declared in this scope
s.wrapper(fun1);
^~~~
try.cpp:23:15: error: ‘fun2’ was not declared in this scope
s.wrapper(fun2);
后来我尝试将 s.fun1() 和 s.fun2() 作为参数传递,但再次出错
try.cpp:23:23: error: invalid use of void expression
s.wrapper(s.fun1());
^
try.cpp:24:23: error: invalid use of void expression
s.wrapper(s.fun2());
请帮助我不知道该怎么办:(
【问题讨论】:
-
普通成员函数指针和类成员函数指针是有区别的。
标签: c++ oop pointers function-pointers member-function-pointers