C++ 函数 - 按引用传递


通过引用传递

在上一页的示例中,我们在将参数传递给函数时使用了普通变量。您还可以通过参考到函数。当您需要更改参数的值时,这会很有用:

示例

void swapNums(int &x, int &y) {
  int z = x;
  x = y;
  y = z;
}

int main() {
  int firstNum = 10;
  int secondNum = 20;

  cout << "Before swap: " << "\n";
  cout << firstNum << secondNum << "\n";

  // Call the function, which will change the values of firstNum and secondNum
  swapNums(firstNum, secondNum);

  cout << "After swap: " << "\n";
  cout << firstNum << secondNum << "\n";

  return 0;
}
亲自试一试 »