按值传递按引用传递按地址传递
按值傳遞:不改變外部對象
按引用傳遞&&按地址傳遞:允許改變外部對象
?
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
//passing by refedrence
void f(int &r)
{
??? cout << "r = " << r << endl;
??? cout << "&r = " << &r << endl;
??? r = 5 ;
??? cout << "r = " << r << endl;
}
//passing by value
void f(int a)
{
??? cout<<"a= "<<a<<endl;
??? a = 5;
??? cout << "a= " << a <<endl;
}
//passing by address
void f(int *p)
{
??? cout << "p = " << p << endl;
??? cout << "*p = " << *p << endl;
??? *p = 5;
??? cout << "p = " << p << endl;
}
int main()
{
//passing by reference
int x = 47 ;
cout << "x = " << x <<endl;
cout << "&x = " << &x << endl;
f(x);//Looks like pass-by-value
????? //is actually pass by reference
cout << "x = " << x << endl;
//output
x = 47
&x = 0x7FFF1D5C9B4C
r = 47
&r = 0x7FFF1D5C9B4C
r = 5
x = 5
//passing by address
int x = 47;
cout << "x = " << x << endl;
cout << "&x = " << &x << endl;
f(&x);
cout << "x = " << x << endl;
//output
x = 47
&x = 0x7FFF9746423c
p = 0x7FFF9746423c
*p = 47
p = 0x7FFF9746423c
x = 5
//passing by value
int x = 97 ;
cout << "x=" << x <<endl;
f(x);
cout << "x=" << x <<endl;
//output
///
x = 47
a = 47
a = 5
x = 47
}
轉載于:https://www.cnblogs.com/shaoguangleo/archive/2010/10/26/2805843.html
總結
以上是生活随笔為你收集整理的按值传递按引用传递按地址传递的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [第180期]我在51CTO的提问:如何
- 下一篇: 随机排序一维数组