#include <iostream>using namespace std;int addition (int a, int b){ int r; r=a+b; return r;}int main (){ int z;int x = 5, y = 3; z = addition (x,y); cout << "The result is " << z;}輸出結果為8
在這種傳遞方式下,x,y的值經過函數處理后是不會改變的。即:
#include <iostream>using namespace std;void duplicate (int a, int b, int c){ a*=2; b*=2; c*=2;}int main (){ int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0;}這樣輸出x,y,z的結果,仍舊是1,3,7
若要調用duplicate函數成功,應用reference的方式傳遞參數。
#include <iostream>using namespace std;void duplicate (int& a, int& b, int& c){ a*=2; b*=2; c*=2;}int main (){ int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0;}這樣輸出的結果就是 2,6,14了。通過之前value的方式在傳遞參數時,當只是int型等數值時并無大礙,但是當參數是一個復雜的混合數據類型。例如:
|
|
string concatenate (string& a, string& b){ return a+b;}但是這樣也會產生問題,a,b的值可能會因為調用函數改變了原本的值,那這樣怎么處理呢?直接上代碼:
string concatenate (const string& a, const string& b){ return a+b;}
新聞熱點
疑難解答
圖片精選