简体   繁体   English

C ++类成员指向全局函数的指针

[英]C++ class member pointer to global function

I want to have a class which has as a member a pointer to a function 我希望有一个类作为成员指向函数的指针

here is the function pointer: 这是函数指针:

typedef double (*Function)(double);

here is a function that fits the function pointer definition: 这是一个适合函数指针定义的函数:

double f1(double x)
{
    return 0;
}

here is the class definion: 这是课堂定义:

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? 或者我必须在函数指针定义中更改某些内容?

Thanks, 谢谢,

Replace this: 替换这个:

class IntegrFunction
{
public:
    Function* function;
};

with this: 有了这个:

class IntegrFunction
{
public:
    Function function;
};

Your typedef already creates a pointer-to-function. 你的typedef已经创建了一个指向函数的指针。 Declaring Function* function creates a pointer-to-pointer-to-function. 声明Function* function创建指向Function* function的指针。

Just replace 只需更换

Function* function;

to

Function function;

You declare the variable as Function* function , but the Function typedef is already a typedef for a pointer. 您将变量声明为Function* function ,但Function typedef已经是指针的typedef。 So the type of the function pointer is just Function (without the *). 所以函数指针的类型只是Function (没有*)。

Replace 更换

typedef double (*Function)(double);

by 通过

typedef double Function(double);

to typedef the function-type. to typedef函数类型。 You can then write the * when using it. 然后,您可以在使用时编写*

您需要使用address-of运算符来获取标准C ++ 03中的函数指针。

func1.function = &f1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM