C或C++中的函数类型

nee*_*eel 3 c c++ pointers function typechecking

我有一个简单的问题:

C或C++中的函数类型是什么

因为我们可以指向C或C++中的函数,这意味着函数应该具有特定类型,否则在指向函数创建的过程中进行类型检查没有任何意义.

有人可以解释我,我是否正确的道路?

如果我走在正确的道路上,我怎样才能找到功能的类型?

Gri*_*han 6

函数指针的语法

C/C++中的函数类型包括return typetypes of input parameters.

请考虑以下函数声明:

int function(char, float);
Run Code Online (Sandbox Code Playgroud)

指向该函数的指针具有以下类型:

int (*funptr)(char, float); 
Run Code Online (Sandbox Code Playgroud)

同样一般:

returntype function (argtype1, argtype2, argtype3)
Run Code Online (Sandbox Code Playgroud)

指向这种功能的相应指针是

returntype (*ptr) (atgtype1, atgtype2, atgtype3);  
Run Code Online (Sandbox Code Playgroud)

有许多不同类型的功能.在这里找到关于函数指针有用参考.

此外,这种分类是基于return type and argument types.功能也可以根据其可访问性范围进行分类.像全局函数,静态函数等.有关简短介绍,请参见此处.


Lol*_*4t0 5

因为每个函数都有它的类型,

例如,函数

double foo(bar& f, const const baz*)
Run Code Online (Sandbox Code Playgroud)

有一种类型

function, that accepts reference to bar and constant pointer to baz and return double
Run Code Online (Sandbox Code Playgroud)

它可以写成

double ()(bar&, const baz*)
Run Code Online (Sandbox Code Playgroud)

指向该函数类型变量的指针将具有类型(可以存储指向该函数的指针的变量)

会有类型

double (*)(bar&, const baz*)
Run Code Online (Sandbox Code Playgroud)

或者,如果您想 typedef 指向该类型函数的指针,您可以编写

typedef double (*func_ptr)(bar&, const baz*)
Run Code Online (Sandbox Code Playgroud)

再次,

func_ptr is a type of pointer to function, that accepts reference to bar and constant pointer to baz and return double
Run Code Online (Sandbox Code Playgroud)

这里的一件事是函数衰减为指向函数的指针,因此您可以编写

func_ptr f = &foo;
Run Code Online (Sandbox Code Playgroud)

func_ptr g = foo;
Run Code Online (Sandbox Code Playgroud)

它会是一样的。


现在想象一下,你有

struct A
{
    double goo(bar& f, const const baz*);
};
Run Code Online (Sandbox Code Playgroud)

现在goo有一种

function of struct A, that accepts reference to bar and constant pointer to baz and return double
Run Code Online (Sandbox Code Playgroud)

指向此函数的指针将具有类型

double (A::*)(bar&, const baz*)
Run Code Online (Sandbox Code Playgroud)

请注意,它的类型不同于自由函数的类型foo。它们根本不兼容。

但是,如果goostatic函数,它属于的事实struct A是不够的(就成员函数需要隐式this参数而static函数不需要)而言。