我得到[错误]无效初始化类型为'float&'的非const引用来自'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);
}
答案 0 :(得分:1)
您正在尝试交换临时对象(由于使用了转换而创建)。此外,在退出交换后将被删除。您不能使用非常量引用绑定临时对象。所以在这样的电话中没有任何意义。完全不清楚为什么你试图将两个整数转换为浮动交换它们。为什么不自己交换整数?
编写类似
的功能void swap( int &a, int &b )
{
int temp = a;
a = b;
b = temp;
}
考虑到已有标准功能std::swap
如果你想在C中编写交换函数,那么它看起来像
void swap( int *a, int *b )
{
int temp = *a;
*a = *b;
*b = temp;
}
答案 1 :(得分:1)
弗拉德是正确的,为什么选择float
?对所有值使用int
。但是,如果您有某种理由这样做,则必须在cast
和references
中保持一致:
#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
将地址传递给函数时,必须以pointer
作为参数。因此void swap(float *a,..
当您需要reference
到变量的地址(作为pointer
传递)时,您使用address of
运算符&
。当您处理作为pointer
传递的值时,为了对values
指向的pointer
进行操作,您必须使用dereference
运算符*
指针。把所有这些放在一起,就得到了上面的代码。 (更容易使用int
... :)
C ++参考 strong>
如果我在你的评论中理解了你想要的东西,你需要这样的东西:
#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
答案 2 :(得分:0)
你必须使用指针(*)获取数组。虽然只通过你必须给&符号(&amp;)。请使用以下代码。
#include <stdio.h>
void swap(int* a, int *b){
float temp=*a;
*a=*b;
*b=temp;
}
main()
{
int a=10, b=5;
swap(&a, &b);
printf("%d \t %d\n",a,b);
}
答案 3 :(得分:0)
在C ++中,您应该使用std::swap
,或者如果您愿意,可以编写自己的模板来交换任意两个值。
template <typename T>
void swap(T & a, T & b)
{
T temp = a;
a = b;
b = temp;
}
int main() {
int a = 10, b = 5;
swap(a, b);
std::cout << a << " \t " << b << std::endl;
return 0;
}
您要完成的任务(将int
视为float
)将导致未定义的行为 - 它可能适用于您的编译器,但它可能很容易在不同的编译器或建筑。如果确实想要,可以使用reinterpret_cast
强制执行此操作。