指向全局函数的C ++类成员指针 [英] C++ class member pointer to global function

查看:97
本文介绍了指向全局函数的C ++类成员指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个类,该类具有指向函数的指针

I want to have a class which has as a member a pointer to a function

这是函数指针:

typedef double (*Function)(double);

这是一个适合函数指针定义的函数:

here is a function that fits the function pointer definition:

double f1(double x)
{
    return 0;
}

这是类别的定义:

class IntegrFunction
{
public:
    Function* function;
};

在主函数中的某处我想做这样的事情:

and somewhere in the main function i want to do something like this:

IntegrFunction func1;
func1.function = f1;

但是,此代码不起作用.

But, this code does not work.

是否可以向类成员分配指向如上所述的全局函数的函数指针?还是我必须更改函数指针定义中的某些内容?

Is it possible to assign to a class member a function pointer to a global function, declared as above? Or do I have to change something in the function pointer definition?

谢谢

推荐答案

替换此:

class IntegrFunction
{
public:
    Function* function;
};

与此:

class IntegrFunction
{
public:
    Function function;
};

您的typedef已经创建了一个函数指针.声明Function* function会创建一个指向函数的指针.

Your typedef already creates a pointer-to-function. Declaring Function* function creates a pointer-to-pointer-to-function.

这篇关于指向全局函数的C ++类成员指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆