目录
按值传递和按引用传递区别
指针,引用传递程序示例
程序理解
按值传递和按引用传递区别
指针,引用传递程序示例
// 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)看起来相同,只有通过原型才知道是按值传递还是按引用传递
人工智能博士
认证博客专家
985AI博士
AI专家
博客专家
王博Kings,985AI博士在读,博客专家,华为云专家,是《机器学习手推笔记》、《深度学习手推笔记》等作者,我的微信:Kingsplusa,欢迎交流学习;在人工智能、计算机视觉、无人驾驶等具有丰富的经验。