C++:值传递、指针传递和引用传递
传递方式 | 函数定义 | 函数调用 | 函数内对a修改的影响 |
---|
值传递 | fun(int a) | fun(a) | 外部a不变 |
指针传递 | fun(int *a) | fun(&a) | 外部a同步更改 |
引用传递 | fun(int &a) | fun(a) | 外部a同步更改 |
#include <string>
#include <iostream>
using namespace std;
void func271(int a)
{
a = 10;
cout <<"值传递:"<<a << endl;
cout << "值传递地址:" << &a << endl;
}
void func272(int* a)
{
*a = 100;
cout << "指针传递:" << *a << endl;
cout << "指针传递地址:" << a << endl;
}
void func273(int &a)
{
a = 1000;
cout << "引用传递:" << a << endl;
cout << "引用传递地址:" << &a << endl;
}
int main(int argc, char* argv[])
{
int a = 1;
cout << "原始值:" << a << endl;
cout << "原始值地址:" << &a << endl;
func271(a);
cout << "值传递a:" << a << endl;
func272(&a);
cout << "指针传递a:" << a << endl;
func273(a);
cout << "引用传递a:" << a << endl;
return 0;
}