我认为我从cplusplus.com和MSDN获得的信息与C++中的"函数定义"完全相同.
int sum(int a, int b)
{
return a + b;
}
Run Code Online (Sandbox Code Playgroud)
该函数可以从程序中的任意数量的位置调用或调用.传递给函数的值是参数,其类型必须与函数定义中的参数类型兼容.
而cplusplus没有,暗示函数的正文(或者它是返回表达式/值?)是它的定义:
重载的函数可能具有相同的定义.例如:
int sum (int a, int b)
{
return a+b;
}
double sum (double a, double b)
{
return a+b;
}
Run Code Online (Sandbox Code Playgroud)
谷歌搜索"函数定义c ++"获得了很多函数的定义,我不关心.
那么,函数的哪些组件构成了它的定义?
我们直截了当地说一些术语:
一些例子:
// 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;
Run Code Online (Sandbox Code Playgroud)
它是签名,用于确定函数(指针)类型,以及在链接器开始将所有内容链接在一起时唯一标识函数的签名+名称.
为什么cplusplus.com说两个函数可以有相同的定义?嗯,这是错的,至少在这个例子中:
int sum(int a, int b) { return a+b; }
double sum(double a, double b) { return a+b; }
Run Code Online (Sandbox Code Playgroud)
虽然函数体看起来相同,但它们表达了不同的基本行为:在整数情况下,+
表示整数加法,在后一种情况下,它是浮点加法.这是两个不同的(内置)运算符.总而言之,这只是一个令人困惑的例子.