Cplusplus 简明教程

C++ Functions

函数是一组共同执行任务的语句。每个 C++ 程序至少有一个函数,其中 main() 是必需的,而所有最简单的程序都可以定义其他函数。

A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.

你可以将代码分成多个函数。如何在不同的函数间分配代码取决于你,但逻辑上通常划分成每个函数执行特定任务的方式。

You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is such that each function performs a specific task.

一个函数 declaration 向编译器声明一个函数的名称、返回类型和参数。一个函数 definition 提供函数的实际主体。

A function declaration tells the compiler about a function’s name, return type, and parameters. A function definition provides the actual body of the function.

C++ 标准库提供了许多内置函数,您的程序可以调用这些函数。例如,函数 strcat() 用于连接两个字符串,函数 memcpy() 用于将一个内存位置复制到另一个位置,还有许多其他函数。

The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.

函数有各种名称,例如方法、子例程、过程等。

A function is known with various names like a method or a sub-routine or a procedure etc.

Defining a Function

C++ 函数定义的一般形式如下所示 −

The general form of a C++ function definition is as follows −

return_type function_name( parameter list ) {
   body of the function
}

C++ 函数定义由函数头和函数主体组成。以下是一个函数的所有部分 −

A C++ function definition consists of a function header and a function body. Here are all the parts of a function −

  1. Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

  2. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.

  3. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

  4. Function Body − The function body contains a collection of statements that define what the function does.

Example

以下是名为 max() 的函数的源代码。此函数采用两个参数 num1 和 num2,并返回两者中较大的一个 −

Following is the source code for a function called max(). This function takes two parameters num1 and num2 and return the biggest of both −

// function returning the max between two numbers

int max(int num1, int num2) {
   // local variable declaration
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result;
}

Function Declarations

一个函数 declaration 向编译器提供有关一个函数名称及其调用的方法的信息。可以单独定义函数的实际主体。

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

一个函数声明有以下部分 −

A function declaration has the following parts −

return_type function_name( parameter list );

对于以上定义的函数 max(),以下是函数声明 −

For the above defined function max(), following is the function declaration −

int max(int num1, int num2);

参数名称在函数声明中并不重要,只需要它们的类型,因此以下也是有效的声明 −

Parameter names are not important in function declaration only their type is required, so following is also valid declaration −

int max(int, int);

在您在一个源文件中定义一个函数并在另一个文件中调用该函数时,需要进行函数声明。在这种情况下,您应当在调用该函数的文件顶部声明该函数。

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Calling a Function

在创建 C++ 函数时,您需要定义函数的用途。要使用一个函数,您需要调用或引用该函数。

While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.

当一个程序调用一个函数时,程序控制权将转移到被调用的函数。被调用的函数执行已定义的任务,当执行其 return 语句或达到其函数结束的右花括号时,它会将程序控制权返回到主程序。

When a program calls a function, program control is transferred to the called function. A called function performs defined task and when it’s return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.

要调用一个函数,您只需要将所需参数与函数名称一起传递,如果函数返回一个值,那么您可以存储该返回的值。例如 −

To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example −

#include <iostream>
using namespace std;

// function declaration
int max(int num1, int num2);

int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
   int ret;

   // calling a function to get max value.
   ret = max(a, b);
   cout << "Max value is : " << ret << endl;

   return 0;
}

// function returning the max between two numbers
int max(int num1, int num2) {
   // local variable declaration
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result;
}

我将 max() 函数与 main() 函数放在一起并编译了源代码。在运行最终的可执行文件时,它会产生以下结果 −

I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result −

Max value is : 200

Function Arguments

如果一个函数要使用参数,则它必须声明接收参数值的变量。这些变量称为函数的 formal parameters

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

形式参数的行为与函数内的其他局部变量相同,在进入函数时创建,在退出时销毁。

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

在调用一个函数时,有两种方法可以将参数传递给一个函数−

While calling a function, there are two ways that arguments can be passed to a function −

Sr.No

Call Type & Description

1

Call by ValueThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

2

Call by PointerThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

3

Call by ReferenceThis method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

默认情况下,C++使用 call by value 来传递参数。一般来说,这意味着函数内的代码不能改变用于调用函数的参数,而上面提到的示例在调用max()函数时使用相同的方法。

By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

Default Values for Parameters

当定义一个函数时,你可以为最后一个参数中的每一个指定一个默认值。如果在调用函数时对应的参数为空,则将使用该值。

When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function.

这是通过使用赋值运算符并在函数定义中为参数赋值来实现的。如果在调用函数时未传递该参数的值,则使用给定的默认值,但如果指定了值,则忽略该默认值,而使用传递的值。考虑以下示例−

This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead. Consider the following example −

#include <iostream>
using namespace std;

int sum(int a, int b = 20) {
   int result;
   result = a + b;

   return (result);
}
int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
   int result;

   // calling a function to add the values.
   result = sum(a, b);
   cout << "Total value is :" << result << endl;

   // calling a function again as follows.
   result = sum(a);
   cout << "Total value is :" << result << endl;

   return 0;
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Total value is :300
Total value is :120