c++ 傳值 傳引用 與 傳指針
#include <iostream>using namespace std;
// 函數(shù)聲明void swap(int x, int y);
int main (){ ? // 局部變量聲明 ? int a = 100; ? int b = 200;
// ? cout << " Before main, a is : " << a << endl;// ? cout << " Before main, b is : " << b << endl;
? /* 調(diào)用函數(shù)來交換值 */ ? swap(a, b);
// ? 單純的傳值,只在調(diào)用的函數(shù)中改變值,原來的值并沒有改變: ? cout << " Just copied a copy to the formal parameter, a is the same a, b is the same b"<< endl; ? cout << " After ?main, a is : " << a << endl; ? cout << " After ?main, b is : " << b << endl;
? return 0;}
// 函數(shù)定義void swap(int x, int y){ ? int temp; ? cout << "--------Before swap --------:"<<endl; ? cout << x <<endl; ? cout << y <<endl; ? temp = x; /* 保存地址 x 的值 */ ? x = y; ? ?/* 把 y 賦值給 x ?*/ ? y = temp; /* 把 x 賦值給 y ?*/ ? cout << "--------After ?swap --------:"<<endl; ? cout << x <<endl; ? cout << y <<endl; ? return;}
// 1 傳值,傳遞實參,即單純的傳值,從內(nèi)存使用的角度來說,傳遞實參,則會將數(shù)據(jù)拷貝過去(創(chuàng)建了副本),// ? 即swap()對傳入的數(shù)據(jù)做任何修改,都不會影響main()。// 2 傳引用// ? 作為形參的引用會指向形參,類似于指針,調(diào)用函數(shù)后,實現(xiàn)了真正的交換。swap()和main()都交換了。// 3 傳指針// ? 類似于傳引用// https://www.runoob.com/cplusplus/passing-parameters-by-references.html