gpt4 book ai didi

c++ - int 参数和 int& 参数的双参数

转载 作者:行者123 更新时间:2023-12-01 15:13:30 26 4
gpt4 key购买 nike

首先,这是《Programming, Principles and Practice Using C++》一书中的一道练习题。这些书故意告诉我写这些函数来理解为什么有些行会导致问题。因此,更改代码不是一种选择。
我能够将双变量或双文字作为参数发送给使用按值传递(int 参数)的 swap_v 函数。
我无法将双变量或双文字作为参数发送给使用按引用传递(int& 参数)的 swap_r 函数。当我使用按值传递时它起作用。
这两行都给出了这 3 个错误。
1-“int &”类型的引用(非 const 限定)不能用“double”类型的值初始化
2- 引用非常量的初始值必须是左值
3- 'void swap_r(int &,int &)': 无法将参数 1 从 'double' 转换为 'int &'

#include <iostream>

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

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

int main()
{
/*
int x = 7;
int y = 9;
swap_v(x, y); // Doesnt swap
swap_v(7, 9); // Cant swap literals.

const int cx = 7;
const int cy = 9;
swap_v(cx, cy); // Doesnt swap
swap_v(7.7, 9.9); // Cant swap literals.

double dx = 7.7;
double dy = 9.9;
swap_v(dx, dy); // Doesnt swap
swap_v(7.7, 9.9); // Cant swap literals.
*/

int x = 7;
int y = 9;
swap_r(x, y); // Swaps
// Doesnt compile. You have to pass variables when using pass by reference.
//swap_r(7, 9);

const int cx = 7;
const int cy = 9;
// Doesnt compile. You cant change constant values.
//swap_r(cx, cy);
// Doesnt compile. You have to pass variables when using pass by reference.
//swap_r(7.7, 9.9);

double dx = 7.7;
double dy = 9.9;
// ???
swap_r(dx, dy);
// ???
swap_r(7.7, 9.9);
}

最佳答案

你可以得到一个int来自 double ,但您无法获得 int&来自 double .
简而言之,这里发生的情况如下:

void foo(int x) {}

double y = 5.0;
foo(y);
y不是 int , 但是一个 double可以转换为 int ,所以基本上你有这个(不是真的,只是为了说明):
double y = 5.0;
int temp = y;
foo(temp);
一个临时的 int传递给函数。现在,如果函数需要引用,你就不能这样做
void bar(int& X) {}

bar(5);
因为你不能绑定(bind) 5到非常量引用。那意味着什么?您不能更改 5 的值.同样, intdouble 转换而来以上只是暂时的并将其作为非常量引用传递,没有任何意义。同样,这并不是真正发生的事情,但它说明了“问题”:
void bar(int& X) {}

double y = 5.0;
int temp = y;
bar(temp);
bar将修改 temp , 但这对 y 没有影响.因为这确实不是转换的工作方式(您的代码中没有明确的 int temp=y;),所以编译器也禁止您这样做
double y = 5.0;
bar(y);
PS 想想如果允许这样的事情会多么令人困惑:
void half(int& x) { x /= 2; }

double x = 3.2;
half(x);
什么是 x现在? 1.6 ? 1 ?来自 double 的转换至 int不是问题,但你如何取回 double ?显然,如果允许这样的事情,它会引起更多的困惑而不是帮助。
PPS swap不是您应该编写的函数。使用 std::swap反而。

关于c++ - int 参数和 int& 参数的双参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60147901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com