本文介绍了函数指针typedef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typedef double F(double)

typdedef double (*FPT)(double);

我可以将两个参数传递给一个函数,即

It seems to me that I can pass both as arguments to a function, i.e.

bar1(FPT f);
bar2(F f);

但我可以做

FPT f = &foo;

我无法做到

F f = foo;

我不能创建类型F的变量。

i.e. I can not create variables of type F?

推荐答案

你在许多方面是正确的。 F 是一个函数类型, FPT 是一个函数指针类型。

You're right in many ways. F is a function type, and FPT is a function pointer type.

如果你有一个函数类型的对象,你可以取它的地址并获得一个函数指针。但是,函数类型的对象不是真正的,一等的C ++对象。只有实际的函数是这样的类型,你不能创建一个对象是一个函数(不是通过声明一个函数!),因此你不能分配给它(如 F f = foo ;

If you have an object of function type, you can take its address and get a function pointer. However, objects of function type aren't real, first-class C++ objects. Only actual functions are of such a type, and you can't create an object that is a function (other than by declaring a function!) and thus you cannot assign to it (as in F f = foo;).

您可以通过函数指针或引用来引用函数的唯一方法是:

The only way you can refer to a function is via a function pointer or reference:

FPT f1 = &foo;
F * f2 = &foo;
F & f3 = foo;

另请参阅。

请注意,对于回调,我宁愿使用指针类型的引用类型,因为它比你通过任何其他变量,因为你可以应用地址和衰减到引用,并获得指针,你不能用一个指针:

Note that for a callback I would prefer the reference type over the pointer type, because it's more natural compared to how you pass any other variable, and because you can apply address-of and decay to the reference and get the pointer, which you can't do with a pointer:

double callme(F & f, double val)       // not: "F *" or "FPT"
{
    return f(val);

    // "&f" and "std::decay<F>::type" still make sense
}

这篇关于函数指针typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:16