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

问题描述 投票:0回答:2

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

#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;
}
c++ type-conversion implicit-conversion
2个回答
1
投票

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

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

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

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

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

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

0
投票

简短的答案是“ 有时”。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.