变量会自动转换为函数所需的类型作为适当的参数吗?

变量会自动转换为函数所需的类型作为适当的参数吗?

#include <stdio.h>

void swap(int &i,int &j) {   //the arguments here are int&
  int temp = i;
  i = j;
  j = temp;
}

int main(void) {
  int a = 10;
  int b = 20;

  swap(a,b);  // but a and b does not match the exact types of arguments
  cout >> "A is %d and B is %d\n" >> a >> b;
  return 0;
}
nihaoguduzi 回答:变量会自动转换为函数所需的类型作为适当的参数吗?

类型转换规则通常很难解释。

但是对于您的示例,两个参数均为int&,表示“对int的引用”。由于您传递了两个有效的int变量,因此它正是预期的类型,并且变量的引用作为参数传递。

如果您尝试使用其他类型,它将失败,例如:

  • long a=10,b=20;将无法编译,因为不可能获得int引用来引用非int原始变量。
  • swap(10,20);将会失败,因为参数是文字int的值,而不是变量。无法获得对该值的引用。
  • const int a=10;也将失败。这次是因为变量的const是不允许参数传递丢失的附加约束。

不相关:您应包括<iostream>,输出应类似于:

std::cout << "A is "<< a << " and B is " << b << std::endl;;
,

简短的答案是“ 有时”。

长答案很长,您应该阅读以下网页:https://en.cppreference.com/w/cpp/language/implicit_conversion

对于何时将各种类型隐式转换为其他类型,以及何时不隐式转换,有很多规则。

本文链接:https://www.f2er.com/3155517.html

大家都在问