Posted on 2007-02-05 21:05
softgamer 閱讀(278)
評論(0) 編輯 收藏 引用 所屬分類:
學(xué)習(xí)日志
引用和引用參數(shù)
?? C++,其實(shí)Java 和 c 都一樣, 調(diào)用函數(shù)的方法有兩種
?? 傳值調(diào)用和引用調(diào)用。
?? 參數(shù)傳值調(diào)用時,會產(chǎn)生該參數(shù)值得副本并將副本傳遞給被調(diào)用的函數(shù),對副本的更改不會影響調(diào)用者的原始變量值,
它的優(yōu)點(diǎn)顯而易見,缺點(diǎn)是復(fù)制數(shù)據(jù)會花費(fèi)較長的時間。
? 引用調(diào)用的優(yōu)點(diǎn)就是避免復(fù)制大量的數(shù)據(jù),但安全性差,因?yàn)楸徽{(diào)用的函數(shù)會直接訪問并修改調(diào)用者的數(shù)據(jù),使用是要格外小心
#include <iostream>
using std::cout;
using std::endl;
int?? pbyValue( int );
void? pByRef ( int & );
int main ()
{
?? ?int x = 2;
?? ?int z = 4;
?? ?cout << "x= " << x << " before pByvalue \n"
?? ??? ? <<"Getting value by pByValue: "
?? ??? ? << pbyValue( x ) << endl
?? ??? ? << "x : " << x << " Got Value\n" <<endl;
?? ?
??? cout << "z= " << z << " before pBy Ref \n" << endl;
?? ??? ?
?? ?pByRef( z );
?? ??? ?
?? ?cout << "z : " << z << " Got Value\n" <<endl;
?? ?
?? ?return 0;
}
int pbyValue ( int a )
{
?? ?return a *= a;
}
void pByRef( int &cRef )
{
?? ?cRef *= cRef;
}