值传递:
形参不会修饰实参
#include<iostream>
using namespace std;
void Swap(int a ,int b)
{
int temp=0;
temp=a;
a=b;
b=temp;
}
int main()
{
int a=10;
int b=20;
Swap(a,b);
std::cout<<a<<emdl;
std::cout<<b<<endl;
}
输出结果为:
10
20
地址传递:
形参修饰实参
#include<iostream>
using namespace std;
void Swap(int* a, int* b)
{
int temp = 0;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a = 10;
int b = 20;
Swap(&a, &b);
std::cout << a << std::endl;
std::cout << b << std::endl;
}
输出为:
20
10
引用传递:
形参修饰实参
#include<iostream>
using namespace std;
void Swap(int& a, int& b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
int b = 20;
Swap(a, b);
std::cout << a << endl;
std::cout << b << endl;
}
输出为 :
20
10
常量引用
使用场景: 修饰形参,防止误操作
引用必须引用一段合法内存空间,不能直接赋值
若写为:int & a=10 错误! int b=10; int&a=b;
可以写为 :const int &a=10; 或者: int temp=10; const int&a=temp;
加入const修饰后,该值不可被修改 如: const int &a=10; a=20; 错误!
使用场景:
#include<iostream>
using namespace std;
void printValue(int &a )
{
cout<<"a="<<a<<endl;;
a=1000;
}
int main()
{
int a=10;
printValue(a);
cout<<"a="<<a<<endl;
}
第二次输出的a=1000;
为防止输入参数(实参)被修改
#include<iostream>
using namespace std;
void printValue(const int &a )
{
cout<<"a="<<a<<endl;;
}
int main()
{
int a=10;
printValue(a);
cout<<"a="<<a<<endl;
}
函数体中不允许修改形参,从而不会改变实参数值。
相比于 值传递 常量修饰的引用 不需要创建额外内存空间进行赋值