形式參數和實際參數:
之前的課程中我們講過函數可以通過return函數傳回相應的值。
在大多數情況下,函數也需要接受一定的參數來進行處理。舉個例子,我們需要一個計算兩個值和的函數。這個時候該函數就需要輸入兩個值。
形式參數就是函數命名的時候括号裡面的參數,多個參數用,隔開。下面是幾個例子:
// 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;
}
每個函數的參數都隻在函數内部有效,是以即使printValue和add函數有相同名字的參數x,其實這兩個x是毫不相關的。
實參就是實際傳遞給函數的參數值如下面所示:
printValue(6); // 6 is the argument passed to function printValue()
add(2, 3); // 2 and 3 are the arguments passed to function add()
實參的數目必須要和形式參數相同,否則編譯器會報錯。
形式參數和實際參數是如何工作的:
當一個函數被調用的時候,函數所有的參數都是作為變量來控制的,每一個變量的值都會比對到相應的參數中。這個過程叫做值傳遞。
//#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;
}
參數和傳回值是怎麼工作的:
通過使用傳回值和參數,我們可以建立一個函數,有輸入值,也有輸出值。下面是一個例子:
//#include "stdafx.h" // Visual Studio users need to uncomment this line
#include <iostream>
// add() takes two integers as parameters, and returns the result of their sum
// The values of x and y are determined by the function that calls add()
int add(int x, int y)
{
return x + y;
}
// main takes no parameters
int main()
{
std::cout << add(4, 5) << std::endl; // Arguments 4 and 5 are passed to function add()
return 0;
}
執行過程如下圖:
下面是一個更加複雜的例子:
//#include "stdafx.h" // Visual Studio users need to uncomment this line
#include <iostream>
int add(int x, int y)
{
return x + y;
}
int multiply(int z, int w)
{
return z * w;
}
int main()
{
std::cout << add(4, 5) << std::endl; // within add(), x=4, y=5, so x+y=9
std::cout << multiply(2, 3) << std::endl; // within multiply(), z=2, w=3, so z*w=6
// We can pass the value of expressions
std::cout << add(1 + 2, 3 * 4) << std::endl; // within add(), x=3, y=12, so x+y=15
// We can pass the value of variables
int a = 5;
std::cout << add(a, a) << std::endl; // evaluates (5 + 5)
std::cout << add(1, multiply(2, 3)) << std::endl; // evaluates 1 + (2 * 3)
std::cout << add(1, add(2, 3)) << std::endl; // evaluates 1 + (2 + 3)
return 0;
}
前兩行非常明确,第三行就是表示算式也可以作為參數,把起最終的計算結果給參數就可以了。
第四種add(a,a),前面定義了a為5。是以函數也就是add(5,5)
第五和第六中都是函數中調用函數,需要從裡往外運算結果。
結論:
參數是使函數具有可重用性的關鍵機制,因為他允許在不知道輸入值的情況下執行任務。這些輸入值被調用者給傳入。
傳回值允許函數傳回一個值給調用者。