变量会自动转换为函数所需的类型作为适当的参数吗?
#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;
}
最佳答案
类型转换规则通常解释起来相当复杂。
但对于您的示例,两个参数都是 int&
,意思是“对 int
的引用”。由于您传递了两个有效的 int
变量,它正是预期的类型,变量的引用作为参数传递。
你会尝试使用不同的类型吗,它会失败,例如:
-
long a=10,b=20;
将无法编译,因为无法获得int
reference 引用非int 原始变量。 -
swap(10,20);
会失败,因为参数是文字int
值而不是变量。无法获得对此类值的引用。 -
const int a=10;
也会失败。这次是因为变量的const是一个额外的约束,参数传递不允许丢失。
不相关:您应该包括 <iostream>
输出应该是这样的:
std::cout << "A is "<< a << " and B is " << b << std::endl;;
关于c++ - 变量会自动转换为函数所需的类型作为适当的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58721739/