值传递
- 特点:形参的变化不改变实参的值
- 定义:
func(int a, int b) - 调用:
func(a,b);
地址传递
- 形参的变化会改变实参的值
- 定义:
func(int *a, int *b) - 调用:
func(&a,&b);
引用传递
- 形参的变化会改变实参的值
- 定义:
func(int &a, int &b) - 调用:
func(a,b);
实例1. 利用三种传递实现值交换
#include<iostream>
using namespace std;
void valueTrans(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
void addrTrans(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void citeTrans(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
int b = 20;
valueTrans(a,b);
cout <<"值传递"<< endl;
cout <<"a = " << a << endl;
cout <<"b = " << b << endl;
addrTrans(&a, &b);
cout <<"地址传递" << endl;
cout <<"a = " << a << endl;
cout <<"b = " << b << endl;
citeTrans(a, b);
cout <<"引用传递" << endl;
cout <<"a = " << a << endl;
cout <<"b = " << b << endl;
return 0;
}
|