【文章內(nèi)容簡介】
scanf( %d%d%d, amp。a, amp。b, amp。c )。 maximum(a,b,c)。 return 0。 } 例子 13:函數(shù)舉例 include void maximum( int x, int y=0, int z=0 ) { int max = x。 if ( y max ) max = y。 if ( z max ) max = z。 printf( Maximum is: %d\n, max )。 return。 /* is not necessary */ } int main() { int a, b, c, max。 printf( Enter three integers: )。 scanf( %d%d%d, amp。a, amp。b, amp。c )。 maximum(a,b,c)。 maximum(a,b)。 maximum(a)。 return 0。 } 例子 14:函數(shù)舉例(錯誤) include void maximum( int x, int y=0, int z=0 ) { int max = x。 if ( y max ) max = y。 if ( z max ) max = z。 printf( Maximum is: %d\n, max )。 return。 /* is not necessary */ } void maximum( int x, int y ) {} int main() { int a, b, c, max。 printf( Enter three integers: )。 scanf( %d%d%d, amp。a, amp。b, amp。c )。 maximum(a,b,c)。 maximum(a,b)。 maximum(a)。 return 0。 } 例子 15:函數(shù)舉例 include int square( char )。 long square( int )。 double square( double )。 int main(){ char c = 127。 int i = 1000。 double d = 。 cout The square of char integer “ (int)c is square( c ) endl。 cout The square of integer i is square( i ) endl。 cout The square of double d is square( d ) endl。 return 0。 } int square( char x ) { return x * x。 } long square( int x ) { return x * x。 } double square( double x ) { return x * x。 } 函數(shù)定義與函數(shù)原型 ? 函數(shù)定義格式 返回值類型說明 函數(shù)名標識符 (形式參數(shù)定義 ) { 語句序列 /*0~n個語句 */ } ? 返回值類型說明 : 省缺是 int ? void 函數(shù)沒有返回值 ? 形式參數(shù)定義:用逗號分隔的參數(shù)說明列表 ? 說明了每個形式參數(shù)的名字、類型以及函數(shù)調(diào)用時的參數(shù)傳遞方式(無參數(shù)則為空或 void) ? {語句序列 }構(gòu)成函數(shù)體 ? 語句序列中的 return語句用于從函數(shù)中返回 函數(shù)定義與函數(shù)原型 ? 函數(shù)原型 ? 函數(shù)名 ? 參數(shù)類型 : 函數(shù)的各形式參數(shù)類型,所帶參數(shù)名被忽略 ? 可定義默認參數(shù) ? 返回值類型:函數(shù)返回值的數(shù)據(jù)類型 (省缺是 int) ? 原型僅在函數(shù)先調(diào)用后定義時用 (向前引用 ) 函數(shù)的調(diào)用 (1/3) ? 調(diào)用函數(shù)時一般要傳遞參數(shù) ? 傳值和傳引用 ? 傳值 ? 把實在參數(shù)的值傳遞給函數(shù)的形式參數(shù) ? 函數(shù)的執(zhí)行對實在參數(shù)沒有影響 ? 函數(shù)不需要修改實在參數(shù)時,用傳值方式 ? 避免意外改變 函數(shù)的調(diào)用 (2/3) ? 傳引用 ? 把實在參數(shù)的地址傳遞給函數(shù)的形式參數(shù) ? 函數(shù)的執(zhí)行可以改變實在參數(shù) ? 函數(shù)確實需要修改實在參數(shù)時,用傳引用方式 ? 要求實在參數(shù)有“左值性質(zhì)” 函數(shù)的調(diào)用 (3/3) ? 默認參數(shù)( 例子 1例子 14) ? 內(nèi)聯(lián)函數(shù)( 例子 12) 函數(shù)重載(例子 15) ? C++允許定義多個同名函數(shù)表示類似的操作 ——函數(shù)重載 ? 這些函數(shù)必須有不同的參數(shù)(參數(shù)的個數(shù)、類型或順序不同) ? 調(diào)用重載函數(shù)時,編譯器通過檢查實在參數(shù)的個數(shù)、類型和順序來確定相應(yīng)的被調(diào)用函數(shù) int abs(int i)。 long abs(long l)。 double abs(double d)。 存儲類別和作用域 (1/9) ? auto,register,extern,static ? 存儲期 : 在內(nèi)存中的存在期 ? 作用域 : 在程序中可以引用該變量的區(qū)域 ? 連接 : 變量在哪些源文件中能夠被識別 ? “最近嵌套原則” 存儲類別和作用域 (2/9) ? 自動存儲 ? 在定義的塊中建立、存在和撤銷 ? auto: 局部變量(包括形式參數(shù))的省缺說明符 ? auto double x, y。 ? register: 為變量分配高速寄存器 ? 只能用于 auto變量 ? register int counter = 1。 存儲類別和作用域 (3/9) ? 靜態(tài)存儲 ? 變量在整個程序運行期間都存在 ? 省缺值為 0 ? static: 可以用于函數(shù)中的局部變量 ? 函數(shù)運行結(jié)束,變量的值依然存在 ? 只能在定義變量的函數(shù)中訪問該變量 ? extern: 全局變量和函數(shù)名的省缺定義