C++ class member pointer to global function

2019-06-19 01:25发布

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,

5条回答
狗以群分
2楼-- · 2019-06-19 01:53

Replace this:

class IntegrFunction
{
public:
    Function* function;
};

with this:

class IntegrFunction
{
public:
    Function function;
};

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

查看更多
贼婆χ
3楼-- · 2019-06-19 01:57

Replace

typedef double (*Function)(double);

by

typedef double Function(double);

to typedef the function-type. You can then write the * when using it.

查看更多
家丑人穷心不美
4楼-- · 2019-06-19 02:01

You declare the variable as Function* function, but the Function typedef is already a typedef for a pointer. So the type of the function pointer is just Function (without the *).

查看更多
不美不萌又怎样
5楼-- · 2019-06-19 02:06

You need to use the address-of operator to obtain a function pointer in Standard C++03.

func1.function = &f1;
查看更多
forever°为你锁心
6楼-- · 2019-06-19 02:15

Just replace

Function* function;

to

Function function;
查看更多
登录 后发表回答