1.关于引用
引用在c++中的表现形式是这样的:
int &b=a;
但千万区分于取地址啊,他的意思并不是取地址。跟在数据类型后的 & 符号即为引用。
关于引用,它常见于函数实参和形参的传递中,因此 引出函数实参和形参的值传递与地址传递两种方式。
2.传参方式
以下为最为常见的三个例子:
(1)值传递(无法实现两变量值的交换)
1 #include <iostream> 2 using namespace std; 3 int main() 4 { 5 int a,b; 6 cin>>a>>b; 7 void swap(int a,int b); 8 swap(a,b); 9 cout<<a<<" "<<b<<endl; 10 11 system("pause"); 12 return 0; 13 } 14 void swap(int a,int b) 15 { 16 int temp; 17 if (a<b) 18 { 19 temp=a; 20 a=b; 21 b=temp; 22 } 23 }
(2)值传递(通过指针实现两变量值的交换)
1 #include <iostream> 2 using namespace std; 3 int main() 4 { 5 int a=1,b=5; 6 // int a,b; 7 /* cin>>a>>b;*/ 8 void swap(int * a,int * b); 9 swap(&a,&b); 10 cout<<a<<" "<<b<<endl; 11 12 system("pause"); 13 return 0; 14 } 15 void swap(int * a,int * b) 16 { 17 int temp; 18 if (*a<*b) 19 { 20 temp=*a; 21 *a=*b; 22 *b=temp; 23 } 24 }
(3)地址传递(采用引用实现值的交换)
1 #include <iostream> 2 using namespace std; 3 int main() 4 { 5 int a,b,c; 6 a=11; 7 b=2; 8 c=103; 9 void three(int &a,int &b,int &c); 10 three(a,b,c); 11 cout<<a<<" "<<b<<" "<<c<<endl; 12 system("pause"); 13 return 0; 14 } 15 void three(int &a,int &b,int &c) 16 { 17 void change(int &a,int &b); 18 if (a>b)change(a,b); 19 if (a>c)change(a,c); 20 if (b>c)change(b,c); 21 } 22 void change(int &a,int &b) 23 { 24 int temp; 25 temp=a; 26 a=b; 27 b=temp; 28 }
以上就是实现两变量交换的方法,由引用引出的值的传递方式。
3.结构体作函数参数
(1)结构体直接作为函数参数(占用内存空间较大,效率不高)
#include<iostream> #include <string> using namespace std; struct student { int num; string name; float score; }; int main() { student stu={20167343,"Mary",99.9}; void print(student stu); print(stu); system("pause"); return 0; } void print(student stu) { cout<<stu.num<<" "<<stu.name<<" "<<stu.score<<endl; }
(2)使用指向结构体的指针,改进方法1的占用内存大的缺点
#include <iostream> using namespace std; struct student { int num; char name[20]; float score; }; int main() { void print(student *p); student stu={20167341,"zhangfan",33.3}; print(&stu); system("pause"); return 0; } void print(student *p) { cout<<(*p).num<<" "<<(*p).name<<" "<<(*p).score<<endl; }
(3)使用 引用 改进前两种方法(虚实结合大大提高了运算的效率)
#include <iostream> using namespace std; struct student { int num; char name[20]; float score; }; int main() { void print(student &p); student stu={20167341,"zhangfan",33.3}; print(stu); system("pause"); return 0; } void print(student &p) { cout<<p.num<<" "<<p.name<<" "<<p.score<<endl; }
4.类的使用与引用
#include<iostream> using namespace std; class Time { //pay attention to this point:we should not miss the word "public" for the reason that //we are gonna to use it in the following functions. public: int hour; int minute; int second; }; int main() { void input(Time&); void dis(Time&); Time t1; input(t1); dis(t1); Time t2; input(t2); dis(t2); system("pause"); return 0; } void input(Time& t) { cin>>t.hour>>t.minute>>t.second; } void dis(Time&t) { cout<<t.hour<<":"<<t.minute<<":"<<t.second<<endl; }