c++ - 在函数上使用 typedef

标签 c++

在下文中,我如何使用 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; }

演示:http://ideone.com/B4d95


至于为什么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/

相关文章:

c++ - 在集成终端上运行 vscode lldb 调试器时如何获取程序的输出?

java对等同于c++

c++ - std::unordered_map 自定义值类型,operator[]

c++ - 使用 fscanf 解析文件

c++ - 尝试在 Codeblocks 上使用 Boost 库会给出未定义的引用

c++ - 对 `Example::Note::~Note()' protobuf 的 undefined reference

c++ - QTest 获取测试名称

c++ - 静态大小的Rcpp空列表是否比list.push_back()更有效?

c++ - 接受 vector 、索引和返回元素的函数

c++ - 在派生构造函数中调用基方法的坏习惯?