函数参数和参数

函数参数和参数
在上一课中,您了解到一个函数可以通过函数的返回值返回一个值返回给调用方。
在许多情况下,能够将信息传递给调用的函数是有用的,这样函数就可以使用。例如,如果我们想写一个函数来添加两个数字,我们需要一种方法来告诉函数,这两个数字添加时,我们称之为。否则,函数如何知道要添加什么?我们通过函数参数和参数。
函数参数是一个函数,在函数中使用函数的调用方提供的函数参数。函数的参数是放在括号的函数标识符后,是用逗号分隔多个参数。

这里有一些不同数量的参数的函数的例子:

// 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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值