c++ - C++ 中的函数定义包含哪些内容?

标签 c++ terminology

我认为我从 cplusplus.com 和 MSDN 获得关于 C++ 中“函数定义”到底是什么的相互矛盾的信息。

MSDN seems to include the parameters :

int sum(int a, int b)
{
    return a + b;
}

The function can invoked, or called, from any number of places in the program. The values that are passed to the function are the arguments, whose types must be compatible with the parameter types in the function definition.

cplusplus does not ,暗示函数的主体(或者它是返回表达式/值?)是它的定义:

Overloaded functions may have the same definition. For example:

int sum (int a, int b)
{
  return a+b;
}

double sum (double a, double b)
{
  return a+b;
}

谷歌搜索“函数定义 C++”得到了很多关于函数是什么的定义,我不关心这些。

那么,函数的哪些组成部分构成了它的定义?

最佳答案

让我们弄清楚一些术语:

  • 函数声明:也称为函数原型(prototype)。它是函数签名名称,没有函数体。相反,它后跟一个分号。
  • 函数定义:函数声明(没有分号)后跟用大括号括起来的代码块,称为函数体
  • 函数签名:函数的返回类型和参数类型。这几乎是函数原型(prototype),不包括名称
  • 函数体:将要执行的实际代码,以大括号括起来的代码块的形式。
  • 函数名:函数原型(prototype)中不是签名的那部分,也就是分号。用于调用函数。

一些例子:

// declaration/prototype
void  // return type
f     // function name
(int) // function parameter list
;     // semicolon
// definition
int g(double) // prototype part of the definition
{ return 42; } // the body, which really "defines" the function
// signature - in between the template's angle brackets < >
std::function<
              int(double)     // this bit is what one would call the signature
                         > h;

确定函数(指针)类型的是签名,当链接器开始将所有内容链接在一起时,签名+名称唯一标识一个函数。

为什么cplusplus.com说两个函数可以有相同的定义?嗯,这是错误的,至少在这个例子中是这样:

int sum(int a, int b)          { return a+b; }
double sum(double a, double b) { return a+b; }

尽管函数体看起来相同,但它们表达了不同的底层行为:在整数情况下,+ 表示整数加法,在后一种情况下,它是浮点加法。这是两个不同的(内置)运算符。总而言之,这只是一个令人困惑的例子。

关于c++ - C++ 中的函数定义包含哪些内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37223737/

相关文章:

c++ - 使用 tun/tap 接口(interface)的错误序列号

c++ - 帮助理解这一点?

swift - 什么是 Objective C 运行时特性?

C++,处理多个构造函数重载和冗余代码

c++ - 无法在初始化中将 'Date' 转换为 'int' 错误

c++ - 比较两个不同的枚举时,是否有避免警告的正确方法?

java - 什么是热点?

compiler-construction - 解析树和抽象语法树(AST)有什么区别?

node.js - Expresso 中的 -I 或 "unshift a path mean"是什么意思?

haskell - Haskell 中的术语 "function application"