excel如何自定义复杂公式计算
872
2025-04-02
成员函数func3=>成员函数func2:
将一个类成员函数的函数指针传递给另一个成员函数是比较简单的,只要定义一个函数指针就可以轻松实现。示例如下:
using namespace std;
class test
{
public:
typedef void (test::*pFUN)();
void func1()
{
func2(&test::func3); //把func3的指针传递给func2
}
void func2(pFUN pfun)
{
(this->*pfun)();
}
void func3()
{
cout<<"test func3."<
}
};
main()
{
void (test::*pfun)() = &test::func3; //把func3的指针赋给pfun
test my_test;
my_test.func1();
my_test.func2(pfun); //把pfun传递给func2
cin.get();
}
输出结果为: test func3. test func3.
void fun(void (*pfun)());
原因:
这是因为类的成员函数是绑定到对象的,对于不同的对象,成员函数将会产生不同的拷贝,这样编译器就不知道把哪个拷贝传给fun了。这种情况在很多地方都会遇到,比如OpenCV里面的鼠标事件回调函数:
void cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, void* param CV_DEFAULT(NULL));
解决办法:
(1)把这个类改成普通的函数。这是最笨的办法。写成类的好处是可以在成员函数之间共享一些数据,如果改成普通的函数,那么就可能会定义一些全局变量来实现共享,而且也不便于管理。
(2)直接把要传递的函数声明为static类型,比如:
static void func3();
程序如下:
#include
using namespace std;
class test
{
public:
friend void friend_fun(void *obj); // 声明一个友元函数
// main中调用外部函数
//void call_fun()
//{
// outside_fun(friend_fun, this); // ☆ 把友元函数的指针和this指针传递给外部函数 ☆
//}
private:
// 私有成员函数
void private_fun()
{
cout<<"test private_func."<
}
};
// ☆ 在 友元函数 中封装调用 私有成员函数private_func ☆
void friend_fun(void *obj)
{
((test*)obj)->private_fun();
}
// ☆ 用友元函数 优于 用static函数 ☆
// 外部的普通函数,接受一个函数指针和一个void指针作为参数,比如多线程的执行函数
void outside_fun(void (*pfun)(void *data), void *data)
{
(*pfun)(data);
}
int _tmain(int argc, _TCHAR* argv[])
{
test* my_test = new test;
//my_test->call_fun();
outside_fun(friend_fun, (void*)my_test);
// 暂停
cin.get();
return 0;
}
输出结果为: test private_func.
网络
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。