C++ premier plus書之--C++函式, 陣列引數與指標的關係1
阿新 • • 發佈:2018-11-28
C++的實參和形參
double cube(double x);
int main()
{
int a = 5;
cube(a);
}
這裡a被稱為實參, x被稱為形參, 形參就是用於接收傳遞值的變數, 實參就是傳遞給函式的值. 形參實際是實參的一個複本. c++中用argument表示實參, 用parameter表示形參.
看個簡單的例子:
// simple function #include "iostream" using namespace std; // 函式原型, 可以不寫變數名, 變數名也可以與函式定義的變數名不同 void n_chars(char, int); int main() { int times; char ch; cout << "Enter a character : "; cin >> ch; while (ch != 'q') { cout << "Enter an integer: "; cin >> times; n_chars(ch, times); cout << "\n Enter another character or press the qsort-key_comp to quit"; cin >> ch; } cout << "times = " << times << endl; cout << "bye\n"; return 0; } // 函式定義 void n_chars(char c, int n) { while (n-- > 0) { cout << c; } }
程式執行結果:
從執行結果可以看出來, 我們最後一次傳遞的實參是10, 函式n_char用以接收的形參n是實參times的一個副本, 雖然函式內對10進行了--操作, 但是不影響main函式中times的數值