Typedeffing一个函数(不是函数指针)

Tho*_*ini 4 c c++ typedef function-pointers

typedef void int_void(int);
Run Code Online (Sandbox Code Playgroud)

int_void 是一个取整数并且什么都不返回的函数.

我的问题是:它可以"单独"使用,没有指针吗?也就是说,是否可以简单地使用它int_void而不是int_void*

typedef void int_void(int);
int_void test;
Run Code Online (Sandbox Code Playgroud)

这段代码编译.但可以test某种方式使用或分配给某些东西(没有演员)?


/* Even this does not work (error: assignment of function) */
typedef void int_void(int);
int_void test, test2;
test = test2;
Run Code Online (Sandbox Code Playgroud)

小智 7

会发生什么,你得到一个较短的函数声明.

你可以打电话test,但你需要一个实际的test()功能.

您无法指定要测试的任何内容,因为它是一个标签,实质上是一个常量值.

您还可以使用int_void在Neil显示时定义函数指针.


typedef void int_void(int);

int main()
{
    int_void test; /* Forward declaration of test, equivalent to:
                    * void test(int); */
    test(5);
}

void test(int abc)
{
}
Run Code Online (Sandbox Code Playgroud)

  • 应该指出的是,typedef可用于声明一个函数,但它不能用于定义函数,这就是为什么在上面的例子中`test`的声明和定义看起来没什么相似之处.据我所知,所有其他typedef的名称都可以用于声明和定义. (3认同)
  • @Andreas,不仅可以让人迷惑,而且GCC:尝试`struct foo {void f(); }; typedef void ftype(); struct bar {friend ftype foo :: f; 看到GCC失败了. (2认同)