// calling.cpp -- defining, prototyping, and calling a function #include <iostream> // function prototype void simple(); int main() { using namespace std; cout << "main() will call the simple() function:\n"; simple(); // function call cout << "main() is finished with the simple() function.\n"; return 0; } // function definition void simple() { using namespace std; cout << "I'm but a simple function.\n"; } 編譯輸出: main() will call the simple() function: I'm but a simple function. main() is finished with the simple() function. ① 執(zhí)行simple()時(shí),,將暫停執(zhí)行main()的代碼; 等simple()執(zhí)行完畢后,繼續(xù)執(zhí)行main()中的代碼,。 ② 每個(gè)函數(shù)定義中,,都使用了一條using編譯指令,因?yàn)槊總€(gè)函數(shù)都使用了cout,。 7.1.1 定義函數(shù)
1. 沒(méi)有返回值的函數(shù)被稱(chēng)為void函數(shù),。語(yǔ)法如下: void functionName (parameterList) { statements; return; // optional } 其中,parameterList指定了傳遞給函數(shù)的參數(shù)類(lèi)型和數(shù)量,;返回語(yǔ)句 return 0; 是可選的,; 2. 有返回值的函數(shù),將生成一個(gè)值,,并將它返回給調(diào)用函數(shù),。語(yǔ)法如下: typeName functionName (parameterList) { statemets; return value; // value is type cast to type typeName } ① 函數(shù)的類(lèi)型被聲明為返回值的類(lèi)型。 ② 對(duì)于有返回值的函數(shù),,必須使用返回語(yǔ)句,,以便將值返回給調(diào)用函數(shù)。值可以是常量,、變量,,也可以是表達(dá)式,,只是其結(jié)果的類(lèi)型必須為typeName類(lèi)型或可以被轉(zhuǎn)換為typeName。然后,,函數(shù)將最終的值返回給調(diào)用函數(shù),。 ③ C++對(duì)于返回值的類(lèi)型有一定的限制:不能是數(shù)組,但可以是其他任何類(lèi)型 — 整數(shù),、浮點(diǎn)數(shù),、指針,結(jié)構(gòu)和對(duì)象,。 通常,,函數(shù)通過(guò)將返回值復(fù)制到指定的CPU寄存器或內(nèi)存單元中將其返回。隨后,,調(diào)用程序?qū)⒉榭丛搩?nèi)存單元,。返回函數(shù)和調(diào)用函數(shù)必須就該內(nèi)存單元中存儲(chǔ)的數(shù)據(jù)類(lèi)型達(dá)成一致。函數(shù)定義計(jì)算返回值,,調(diào)用函數(shù)尋找返回值,。 函數(shù)在執(zhí)行返回語(yǔ)句后結(jié)束。如果函數(shù)包含多條返回語(yǔ)句,,則函數(shù)在執(zhí)行遇到的第一條返回語(yǔ)句后結(jié)束,。 7.1.2 函數(shù)原型和函數(shù)調(diào)用
#include <iostream> void cheers(int); // prototype: no return value double cube(double x); // prototype: return a double int main() { using namespace std; cheers(5); // function call cout << "Give me a number: "; double side; cin >> side; double volume = cube(side); // function call cout << "A " << side << "-foot cube has a volume of " << volume << " cubic feet.\n"; cheers(cube(2)); // prototype protection at work return 0; } void cheers(int n) { using namespace std; for (int i = 0; i < n; i++) cout << "Cheers! "; cout << endl; } double cube(double x) { return x * x * x; } 編譯輸出: Cheers! Cheers! Cheers! Cheers! Cheers! Give me a number: 5 A 5-foot cube has a volume of 125 cubic feet. Cheers! Cheers! Cheers! Cheers! Cheers! Cheers! Cheers! Cheers! ① 只有在函數(shù)使用了名稱(chēng)空間std中的成員時(shí),,才在該函數(shù)中使用了using編譯指令。 ② main()使用函數(shù)名和參數(shù)來(lái)調(diào)用void類(lèi)型的函數(shù),。 ③ 由于cube()有返回值,,因此main()可以將其用在賦值語(yǔ)句中。
|
|
來(lái)自: Cui_home > 《7. 函數(shù)—C++的編程模塊》