写在前面:作为一只小白,感谢小甲鱼老师提供这么好的入门课程。因此在这里做个笔记,如有侵权请联系删除
www.fishc.com
传值、传址和传引用
① 传值方式
#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;
}
运行结果
My age is 24
In this, my age is 25
Now my age is 24
②传址方式
#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;
}
运行结果
My age is 24
In this, my age is 25
Now my age is 25
③ 引用传递
#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;
}
运行结果
请输入两个不同的值: 1
2
转换后输出: 2 1