C++参数传递-复制和引用

使用引用实质还是指针,使用引用的好处:

  1. 可以更加简洁的书写代码
  2. 可以直接传递某个对象,而不只是把对象复制一份。 
 1 #include <iostream>
 2 using namespace std;
 3 void swap1(int,int);
 4 void swap2(const int&, const int&);  //const 可以将参数变成只读,无法更改。
 5 
 6 int main()
 7 {
 8     int num1 = 10,num2= 5;
 9     swap1(num1,num2);
10     cout << " After swaping1:"<<num1<<'\t'<<num2<<endl;   // 10,  5
11     swap2(num1,num2);
12     cout << " After swaping2:"<<num1<<'\t'<<num2<<endl;   //  5,  10
13 return 0 ;
14 }
15 void swap1(int num1,int num2)
16 {
17     int temp = num1;
18     num1= num2;
19     num2 = temp;
20 
21 }
22 void swap2(int& ref1,int& ref2)
23 {
24     int temp;
25     temp= ref1;
26     ref1 = ref2;
27     ref2 = temp;
28 
29 }

 

引用在函数的参数传递时的好处:

  1. 较大的对象或数据,用引用省内存,只需传地址程序效率高。
  2. 参数传递时,不产生副本。
  3. 增加const,保证安全
posted @ 2019-08-27 15:03  Parallax  阅读(658)  评论(0编辑  收藏  举报