gpt4 book ai didi

c++ - 一道C++面试题的疑惑

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:05:34 25 4
gpt4 key购买 nike

我已阅读 Answers to C++ interview questions其中有一个让我很疑惑:

Q: When are temporary variables created by C++ compiler?

A: Provided that function parameter is a "const reference", compiler generates temporary variable in following 2 ways.

a) The actual argument is the correct type, but it isn't Lvalue

double Cube(const double & num)
{
num = num * num * num;
return num;
}

double temp = 2.0;
double value = cube(3.0 + temp); // argument is a expression and not a Lvalue

b) The actual argument is of the wrong type, but of a type that can be converted to the correct type

 long temp = 3L;
double value = cuberoot(temp); // long to double conversion

我的问题是一旦函数参数是一个const 引用,为什么编译器会生成临时变量,这不是自相矛盾吗?另外,函数 Cube 是否应该因为修改了 const 参数而无法编译?

最佳答案

我看不出有什么自相矛盾的地方。如果参数不是左值,或者类型错误,则由于显而易见的原因,不能将引用直接附加到参数;因此需要正确类型的中间临时文件。引用附加到该临时文件。

Cube 函数确实被破坏了(格式错误),因为它试图修改一个 const 值。

关于c++ - 一道C++面试题的疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3857728/

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