c++ - 通过不同类型的引用传递参数时如何打字

标签 c++ casting

我不知道如何转换它。我尝试的一切总是失败。下面的代码显示了它

#include <iostream>

using namespace std;

void swaps(int &a, int &b){
    int temp; 
    temp = a, 
    a=b; 
    b=temp; 
    }

int main(){
    double dx = 7.7;    
    double dy = 9.9;

    //it's ok if dx is int
    //it's ok if dy is int

    swaps(int(dx),int(dy));                                  //#1
    swaps((int) dx,(int)dy);                                 //#2
    swaps(static_cast<int>(dx),static_cast<int>(dy));        //#3

    return 0;
    }

因此,如果您能帮助我解决问题,我将非常感谢您。谢谢 :)

最佳答案

问题

在这种情况下,类型转换将生成 rvalue

另请:Is it an Rvalue or Lvalue After a Cast

将这些右值传递给非常量左值引用接收它的函数会导致错误。

换句话说,您的类型转换变量不是原始变量。因此,交换这些类型转换的值是没有意义的。

您可以看到this来获取C++中的左值和右值的图片。



您可以阅读以下内容以了解有关您的问题的更多信息:

Error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’

但是,此处建议的解决方案不适用于您的交换函数,因为它必须通过非const引用接受参数。但是通过类型转换产生的右值不允许您这样做。

如果您尝试通过右值引用获取参数,则代码将编译,但与其交换原始变量,不如交换原始变量。这是一些代码来说明这一点:

#include <iostream>

using namespace std;

void swap(int&& a, int&& b) // rvalue reference (universal reference)
{
    cout << "Inside the swap function:-\n";
    cout << "a = " << a << '\n'; // 7
    cout << "b = " << b << '\n'; // 9

    int tmp;
    tmp = a;
    a = b;
    b = tmp;

    // You can process the swapped variables inside the function
    cout << "After Swapping:-\n";
    cout << "dx = " << a << '\n'; // 9
    cout << "dy = " << b << '\n'; // 7
}

int main()
{
    double dx = 7.7;
    double dy = 9.9;

    // Now this will compile       
    swap(static_cast<int>(dx), static_cast<int>(dy));

    // The function had swapped those temporary rvalues produced by the typecast
    // So you will not have the effect of swap outside the function
    cout << "Outside the swap function:-\n";
    cout << "dx = " << dx << '\n'; // 7.7
    cout << "dy = " << dy << '\n'; // 9.9
    return 0;
}

您可以检查this以开始使用右值引用并移动语义。

更好的解决方案是使用模板化的 swap函数,而不是在传递参数时依赖于类型转换:
template <typename T>
void swap(T& a, T& b)
{
    T temp; 
    temp = a; 
    a = b; 
    b = temp; 
}

您可以在不强制转换原始变量的情况下调用此函数,并且可以在函数内部和外部进行交换。

如果您不知道什么是模板,则可以从here开始。

顺便说一下,C++具有内置的交换函数 std::swap 。如您所见,即使这样也要依靠模板而不是类型转换来避免出现类似情况的问题。

关于c++ - 通过不同类型的引用传递参数时如何打字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60463061/

相关文章:

c - 未初始化指针的可能输出

c - printf 的类型转换,但其他情况则不然

c++ - 反汇编二进制文件中的 HIGHLOW 是什么意思?

c++ - 双C++的精度损失

c++ - 发现用户是否具有管理员权限

c++模板类型推导在强制转换运算符中失败

c++ - 使用 C++ 的父类(super class)和子类中的继承给出错误

c++ - CopyMemory 非 POD

c++ - 在模板方法中使用模板类中的模板类

c - 连续应用两个显式指针转换?