2012-04-05

Call by value , address , reference

用函數的資料傳遞有三個方式:by value, address, reference.

用 call by value:
通常只是計算上的額外參考參數,若需要結果就使用 return。

用 call by address, reference:
通常用在大型的資料傳遞上,例如物件、陣列這種情況,
好處是可以避免函數額外建立相對應的區域變數,浪費額外的空間來複製資料。
基本用法:

void Call_by_reference(int &tmp);
void Call_by_address(int *tmp);

void main()
{

     int a = 555;
     cout<<"init a = "<<a<<endl;


      Call_by_reference(a);
      cout<<"Call_by_reference = "<<a<<endl;


      Call_by_address(&a);
      cout<<"Call_by_address = "<<a<<endl;

      system("pause");
}

void Call_by_reference(int &tmp)
{
      tmp = 100;
}


void Call_by_address(int *tmp)
{
      *tmp = 200;

}

沒有留言:

張貼留言