函数参数和参数
在上一课中,您了解到一个函数可以通过函数的返回值返回一个值返回给调用方。
在许多情况下,能够将信息传递给调用的函数是有用的,这样函数就可以使用。例如,如果我们想写一个函数来添加两个数字,我们需要一种方法来告诉函数,这两个数字添加时,我们称之为。否则,函数如何知道要添加什么?我们通过函数参数和参数。
函数参数是一个函数,在函数中使用函数的调用方提供的函数参数。函数的参数是放在括号的函数标识符后,是用逗号分隔多个参数。
参数和参数如何一起工作
当调用一个函数时,函数的所有参数都被创建为变量,每个参数的值都被复制到匹配参数中。这个过程被称为“按值传递。
例如:
在上一课中,您了解到一个函数可以通过函数的返回值返回一个值返回给调用方。
在许多情况下,能够将信息传递给调用的函数是有用的,这样函数就可以使用。例如,如果我们想写一个函数来添加两个数字,我们需要一种方法来告诉函数,这两个数字添加时,我们称之为。否则,函数如何知道要添加什么?我们通过函数参数和参数。
函数参数是一个函数,在函数中使用函数的调用方提供的函数参数。函数的参数是放在括号的函数标识符后,是用逗号分隔多个参数。
这里有一些不同数量的参数的函数的例子:
// This function takes no parameters
// It does not rely on the caller for anything
void doPrint()
{
std::cout << "In doPrint()" << std::endl;
}
// This function takes one integer parameter named x
// The caller will supply the value of x
void printValue(int x)
{
std::cout << x << std::endl;
}
// This function has two integer parameters, one named x, and one named y
// The caller will supply the value of both x and y
int add(int x, int y)
{
return x + y;
}
值得注意的是,多个参数也用逗号隔开。参数的数目必须与函数参数的数目相匹配。否则,编译器将抛出一个错误。
参数和参数如何一起工作
当调用一个函数时,函数的所有参数都被创建为变量,每个参数的值都被复制到匹配参数中。这个过程被称为“按值传递。
例如:
//#include "stdafx.h" // Visual Studio users need to uncomment this line
#include <iostream>
// This function has two integer parameters, one named x, and one named y
// The values of x and y are passed in by the caller
void printValues(int x, int y)
{
std::cout << x << std::endl;
std::cout << y << std::endl;
}
int main()
{
printValues(6, 7); // This function call has two arguments, 6 and 7
return 0;
}