我收到[错误]从“float”类型的右值对“float&”类型的非常量引用进行无效初始化
#include <stdio.h>
void swap(float &a, float &b){
float temp=a;
a=b;
b=temp;
}
main()
{
int a=10, b=5;
swap((float)a, (float)b);
printf("%d%d",a,b);
}
最佳答案
Vlad 是正确的,为什么要转换为 float
?对所有值使用 int
。但是,如果您出于某种原因这样做,则您的 Actor
和引用
必须保持一致:
#include <stdio.h>
void swap(float *a, float *b){
float temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int a=10, b=5;
swap((float*)&a, (float*)&b);
printf("\n%d%d\n\n",a,b);
return 0;
}
输出:
$ ./bin/floatcast
510
当您将地址传递给函数时,它必须采用指针
作为参数。因此,void swap(float *a,..
) 当您需要对变量地址的引用
(作为指针
传递)时,您使用地址
运算符&
。当您处理作为指针
传递的值时,以便对值进行操作
指针
指向的code>,您必须使用*
运算符取消引用
指针。将所有这些放在一起,您就得到了上面的代码。(使用 int
更容易... :)
C++ 引用
如果我明白你在评论中想要什么,你想要这样的东西:
#include <iostream>
// using namespace std;
void swap(float& a, float& b){
float temp=a;
a=b;
b=temp;
}
int main()
{
int a=10, b=5;
swap ((float&)a, (float&)b);
std::cout << std::endl << a << b << std::endl << std::endl;
return 0;
}
输出:
$ ./bin/floatref
510
关于c++ - 与非常量引用参数交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27328857/