C++ 指针与函数
在本教程中,我们将通过示例了解在 C++ 中将指针作为参数传递给函数。
在C++ 函数教程中,我们学习了向函数传递参数。使用的这种方法称为按值传递,因为传递的是实际值。
但是,还有另一种向函数传递参数的方法,其中不传递参数的实际值。而是传递对值的引用。
例如,
// 值传递
void func1(int numVal) {
// code
}
// 应用传递
void func2(int &numRef) {
// code
}
int main() {
int num = 5;
// pass by value
func1(num);
// pass by reference
func2(num);
return 0;
}
注意在 void func2(int &numRef)
中的 &
, 这表示我们使用变量的地址作为我们的参数。
所以,当我们在 main()
中通过传递 num
变量作为参数来调用 func2()
函数时,我们实际上传递的是 num
的地址而不是值 5
。
示例 1:无指针通过引用传递
#include <iostream>
using namespace std;
// function definition to swap values
void swap(int &n1, int &n2) {
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
// initialize variables
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
// call function to swap numbers
swap(a, b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
输出
Before swapping
a = 1
b = 2
After swapping
a = 2
b = 1
在这个程序中,我们传递了变量 a
和 b
到 swap()
函数。注意函数定义,
void swap(int &n1, int &n2)
在这里,我们使用 &
来表示该函数将接受地址作为其参数。
因此,编译器可以识别将变量的引用传递给函数参数而不是实际值。
在 swap()
函数中,函数参数 n1
和 n2
分别指向与变量 a
和 b
相同的值。因此,交换发生在实际价值上。
可以使用指针完成相同的任务。要了解指针,请访问C++ 指针。
示例 2:使用指针按引用传递
#include <iostream>
using namespace std;
// function prototype with pointer as parameters
void swap(int*, int*);
int main()
{
// initialize variables
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
// call function by passing variable addresses
swap(&a, &b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
// function definition to swap numbers
void swap(int* n1, int* n2) {
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
输出
Before swapping
a = 1
b = 2
After swapping
a = 2
b = 1
在这里,我们可以看到输出与前面的示例相同。注意这一行,
swap(&a, &b);
在这里,在函数调用期间传递的是变量的地址而不是变量。
由于传递的是地址而不是值,因此必须使用 *
来访问存储在该地址中的值。
temp = *n1;
*n1 = *n2;
*n2 = temp;
*n1
和 *n2
分别给出存储在 n1
和 n2
地址处的值。
因为 n1
和 n2
包含 a
和 b
的地址, 任何对 *n1
和 *n2
的操作将改变 a
和 b
的实际值。
因此,当我们在 main()
函数中打印 a
和 b
时,他们的值发生了变化。