传值、传址和传引用
1、传值方式
#include <iostream>
using namespace std;
void changeAge(int age, int newage);
int main()
{
int age = 24;
cout << "My age is " << age << endl;
changeAge(age, age+1);
cout << "Now my age is " << age << endl;
return 0;
}
void changeAge(int age, int newage)
{
age = newage;
cout << "In this, my age is " << age << endl;
}
2、传址方式
#include <iostream>
using namespace std;
void changeAge(int *age, int newage);
int main()
{
int age = 24;
cout << "My age is " << age << endl;
changeAge(&age, age+1);
cout << "Now my age is " << age << endl;
return 0;
}
void changeAge(int *age, int newage)
{
*age = newage;
cout << "In this, my age is " << *age << endl;
}
练习:
#include <iostream>
using namespace std;
void swap(int *x, int *y);
int main()
{
int x, y;
cout << "请输入两个不同的值: ";
cin >> x >> y;
swap(&x, &y);
cout << "转换后输出: " << x << ' ' << y << endl;
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
思考:
另外一种不需要中介的互换方案:
采用异或操作
#include <iostream>
using namespace std;
void swap(int *x, int *y);
int main()
{
int x, y;
cout << "请输入两个不同的值: ";
cin >> x >> y;
swap(&x, &y);
cout << "转换后输出: " << x << ' ' << y << endl;
return 0;
}
void swap(int *x, int *y)
{
//采用异或操作
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
异或可以用于交换两个数举例:
例如x和y转换成二进制后分别为10110和11011
那么
x = x^y = (10110)^(11011) = 01101
y = y^x = (11011)^(01101) = 10110
x = x^y = (01101)^(10110) = 11011
因此达到交换的目的
3、引用传递
#include <iostream>
using namespace std;
void swap(int &x, int &y);
int main()
{
int x, y;
cout << "请输入两个不同的值: ";
cin >> x >> y;
swap(x, y);
cout << "转换后输出: " << x << ' ' << y << endl;
return 0;
}
void swap(int &x, int &y)
{
int temp;
temp = x;
x = y;
y = temp;
}
注意传址传递和引用传递的区别:感觉传址传递是交换的地址中的值,而引用传递是交换地址.