#include <iostream> #include <string> using namespace std; //值传递:(传值调用) //效果上:方法内的改变不会影响到方法外 //本质上:只改变了形参的值,并没有改变实参的值 //条件上:形参的类型为基本类型或者一般复杂类型 void swap(int num1,int num2) //传值调用 { int temp; temp = num1; num1 = num2; num2 = temp; cout << "swap: " << num1 << " " << num2 << endl; } //引用传递:(地址传递)(传址调用) //效果上:方法内的改变会影响到方法外 //本质上:通过形参指针去改变了实参的值 //条件上:形参为指针和数组和引用时一般都是引用传递,(特殊情况:当函数内只改变了指针的指向,而没有通过指针去修改实参值时,仍然是传值调用) void swap_point(int *num1,int *num2) //传址调用 { int temp; temp = *num1; *num1 = *num2; *num2 = temp; cout << "swap_point:" << *num1 << " " << *num2 << endl; } void swap_value(int *num1,int *num2) //传值调用 { int *temp; temp = num1; num1 = num2; num2 = temp; cout << "swap_value :" << *num1 << " " << *num2 << endl; } void swap_two(int **num1,int **num2) //传址调用 { int *temp = NULL; temp = *num1; *num1 = *num2; *num2 = temp; cout << "swap_two: " << **num1 << " " << **num2 << endl; } void swap_ref(int &num1,int &num2) //传址调用 { int temp; temp = num1; num1 = num2; num2 = temp; cout << "swap_ref " << num1 << " " << num2 << endl; } int main() { int a = 10,b = 20; cout << "a = " << a << "b = " << b << endl; #if 0 swap(a,b); #endif #if 0 swap_point(&a,&b); #endif #if 0 swap_value(&a,&b); #endif #if 0 int *p1 = &a,*p2 = &b; cout << *p1 << " " << *p2 << endl; swap_two(&p1,&p2); cout << "a = " << *p1 << "b = " << *p2 << endl; #endif swap_ref(a,b); cout << a << " " << b << endl; }
时间: 2024-10-12 20:33:28