【C++】引用变量--2.将引用作为函数参数
【摘要】 目录
按值传递和按引用传递区别
指针,引用传递程序示例
程序理解
按值传递和按引用传递区别
指针,引用传递程序示例
// swaps.cpp -- 使用指针和引用来进行交换#include<iostream> void swapr(int & a, int & b); void swapp(int * p, int * q);void swapv(int...
目录
按值传递和按引用传递区别
指针,引用传递程序示例
-
// swaps.cpp -- 使用指针和引用来进行交换
-
#include<iostream>
-
-
void swapr(int & a, int & b);
-
void swapp(int * p, int * q);
-
void swapv(int a, int b);
-
-
int main()
-
{
-
using namespace std;
-
int wallet1 = 300;
-
int wallet2 = 350;
-
cout << "--------------------" << endl;
-
cout << "wallet1 = $" << wallet1;
-
cout << "wallet2 = $" << wallet2 << endl << endl;
-
-
cout << "--------------------" << endl;
-
cout << "Using references to swap contents: \n";
-
swapr(wallet1, wallet2);
-
cout << "wallet1 = $" << wallet1;
-
cout << "wallet2 = $" << wallet2 << endl << endl;
-
-
cout << "--------------------" << endl;
-
cout << "Using pointer to swap contents again:\n";
-
swapp(&wallet1, &wallet2);
-
cout << "wallet1 = $" << wallet1;
-
cout << "wallet2 = $" << wallet2 << endl << endl;
-
-
cout << "--------------------" << endl;
-
cout << "Trying to use passing by value:\n";
-
swapv(wallet1, wallet2);
-
cout << "wallet1 = $" << wallet1;
-
cout << "wallet2 = $" << wallet2 << endl << endl;
-
return 0;
-
-
}
-
-
void swapr(int & a, int & b)//使用引用
-
{
-
int temp;
-
-
temp = a;
-
a = b;
-
b = temp;
-
}
-
-
void swapp(int * p, int * q)
-
{
-
int temp;
-
-
temp = *p;
-
*p = *q;
-
*q = temp;
-
}
-
-
void swapv(int a, int b)
-
{
-
int temp;
-
-
temp = a;
-
a = b;
-
b = temp;
-
}
程序理解
按引用传递swapr(wallet1, wallet2)和按值传递swapv(wallet1, wallet2)看起来相同,只有通过原型才知道是按值传递还是按引用传递
文章来源: kings.blog.csdn.net,作者:人工智能博士,版权归原作者所有,如需转载,请联系作者。
原文链接:kings.blog.csdn.net/article/details/90452105
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)