其他分享
首页 > 其他分享> > 值传递,引用传递,地址传递

值传递,引用传递,地址传递

作者:互联网

// reference.cpp : 定义控制台应用程序的入口点。

#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <vector>

using namespace std;

//函数声明
void Swap1(int pNum1, int pNum2);
void Swap2(int& pNum1, int& pNum2);
void Swap3(int* pNum1, int* pNum2);
void Swap4(int* pNum1, int* pNum2);

int _tmain(int argc, _TCHAR* argv[])
{
	//实际变量
	int nNum1 = 5;
	int nNum2 = 8;
	cout << "初始值" << "\t" << nNum1 << endl;
	cout << "初始值" << "\t" << nNum2 << endl;
	cout << endl;
	
	Swap1(nNum1, nNum2);
	cout << "外部变量" << "\t" << nNum1 << endl;
	cout << "外部变量" << "\t" << nNum2 << endl;
	cout << endl;
	
	Swap2(nNum1, nNum2);
	cout << "外部变量" << "\t" << nNum1 << endl;
	cout << "外部变量" << "\t" << nNum2 << endl;
	cout << endl;
	
	Swap3(&nNum1, &nNum2);
	cout << "外部变量" << "\t" << nNum1 << endl;
	cout << "外部变量" << "\t" << nNum2 << endl;
	cout << endl;
	
	Swap4(&nNum1, &nNum2);
	cout << "外部变量" << "\t" << nNum1 << endl;
	cout << "外部变量" << "\t" << nNum2 << endl;
	cout << endl;
	
	system("pause");
	return 0;
}

//值传递:创建临时变量副本,操作的是临时变量
void Swap1(int nNum1, int nNum2){
	int nTemp = nNum1;
	nNum1 = nNum2;
	nNum2 = nTemp;
	cout << "nNum1值传递" << "\t" << nNum1 << endl;
	cout << "nNum2值传递" << "\t" << nNum2 << endl;
}

//引用传递:直接通过引用操作外部变量
void Swap2(int& nNum1, int& nNum2){
	int nTemp = nNum1;
	nNum1 = nNum2;
	nNum2 = nTemp;
	cout << "nNum1引用传递" << "\t" << nNum1 << endl;
	cout << "nNum2引用传递" << "\t" << nNum2 << endl;
}

//地址传递:创建指针副本,通过指针副本操作地址,从而操作外部变量
void Swap3(int* pNum1, int* pNum2)
{
	int nTemp = *pNum1;
	*pNum1 = *pNum2;
	*pNum2 = nTemp;
	cout << "*pNum1地址传递" << "\t" << *pNum1 << endl;
	cout << "*pNum2地址传递" << "\t" << *pNum2 << endl;
}

//地址交换:通过交换指针(地址)来交换所存的值,但不修改外部变量的值
void Swap4(int* pNum1, int* pNum2)
{
	int* pTemp = pNum1;
	pNum1 = pNum2;
	pNum2 = pTemp;
	cout << "*pNum1地址交换" << "\t" << *pNum1 << endl;
	cout << "*pNum2地址交换" << "\t" << *pNum2 << endl;
}

标签:nTemp,int,nNum2,传递,地址,pNum1,引用,pNum2,cout
来源: https://blog.csdn.net/weixin_40968046/article/details/115119963