C++ 函数通过指针调用

C++ 函数通过指针调用

通过指针传递参数的 调用方法 将参数的地址复制到形式参数中。在函数内部,使用该地址来访问调用中使用的实际参数。这意味着对参数所做的更改会影响传递的参数。

要通过指针传递值,需要将参数指针传递给函数,就像传递任何其他值一样。因此,需要将函数参数声明为指针类型,如下所示的 swap() 函数,它交换其参数指向的两个整数变量的值。

// function definition to swap the values.
void swap(int *x, int *y) {
   int temp;
   temp = *x; /* save the value at address x */
   *x = *y; /* put y into x */
   *y = temp; /* put x into y */

   return;
}

要了解有关C++指针的详细信息,请查看 C++指针 章节。

现在,让我们通过指针传递值来调用函数 swap() ,就像以下示例中一样。

#include <iostream>
using namespace std;

// function declaration
void swap(int *x, int *y);

int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;

   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;

   /* calling a function to swap the values.
      * &a indicates pointer to a ie. address of variable a and 
      * &b indicates pointer to b ie. address of variable b.
   */
   swap(&a, &b);

   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;

   return 0;
}

当上述代码放在一个文件中编译并执行时,会产生以下结果−

Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程