#include<iostream.h> void swap(int *,int *); void swap2(int &,int &); void swap3(int []); int main(){ int a=3,b=8; cout<<a<<","<<b<<endl; swap(&a,&b); cout<<a<<","<<b<<endl; swap2(a,b); cout<<a<<","<<b<<endl; } void swap(int *a,int *b){//交换数据 int temp=*a; *a=*b; *b=temp; } void swap2(int &a,int &b){//引用传递参数 int temp=a; a=b; b=temp; } void swap2(int numb[]){ int a=numb[0]; numb[0]=numb[1]; numb[1]=a; }
从上面的代码中可以看到指针和引用都可以传递参数并改变值,传递的是地址。数组是引用传递,传递的是数组的首地址,在函数里面发生变化后会改变数组的值。
参数的传递之二。(集合的传递如vector)
std::vector<int> li; for(i=0;i<10;i++)li.push_back(100-i); //初始化 swap4(li); swap5(li);//等同于swap5(getLi()); void swap4(std::vector<int> q){ //函数调用 for(int i=0;i<q.size();i++) q[i]=i*2; } void swap5(std::vector<int>& li){ //使用引用接收向量集合 for(int i=0;i<li.size();i++)li[i]=2*i+1; } std::vector<int>& getLi(){ return li; //其中li的类型是std::vector<int> }
swap4()函数调用之后,不会改变集合里面的值。使用引用接收集合会改变内容,引用接收的是地址,getLi()返回的仅仅是内容而已
引用的使用:
int one=3; int &rInt=one;//rInt引用作为one的别名来使用 int *ip=&one;//是取地址操作符 cout<<&one<<&rInt<<endl;//表示变量和引用取地址。
使用引用传递参数来改变参数,如上swap2().
使用引用作为返回值
扫描二维码关注公众号,回复:
544926 查看本文章
#include<iostream.h> float temp; float fn1(float r){ temp=r*r*3.14; return temp; } float& fn2(float r){ temp=r*r*3.14; return temp } int main(){ float a =fn1(5.0); float& b=fn1(5.0); //waring float c =fn2(5.0); //程序的效率和空间利用率较高 float& d=fn2(5.0); }