在下文中,我如何使用 typedef 语法定义我的函数?
typedef void F();
//declare my function
F f;
//error
F f { }
最佳答案
函数的定义将遵循通常的语法:
//declare my function
F f; //it is exactly equivalent to : void f();
//definition
void f() { cout << "hello world"; }
要测试该定义确实是之前声明的函数的定义,只需调用函数f()
>after 声明和before 定义(阅读main()
中的注释):
//declaration
F f;
int main()
{
f(); //at compile-time, it compiles because of *declaration*
}
//definition
void f() { std::cout << "hello world" << std::endl; }
至于为什么F f{}
不行,因为语言规范明确禁止。 §8.3.5 (C++03) 说
A typedef of function type may be used to declare a function but shall not be used to define a function (8.4).
[Example:
typedef void F();
F fv; // OK: equivalent to void fv();
F fv { } // ill-formed
void fv() { } // OK: definition of fv
—end example]
要点:
- 函数的 typedef 可用于声明函数
- 函数的 typedef 不能用于定义函数
关于c++ - 在函数上使用 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309698/