[英]Passing through reference a parameter to a function C++
Let's suppose this code: 让我们假设这段代码:
void function(double &f){
// doing w/e here
}
then in the main function: 然后在主要功能:
float v;
function(&v);
My compiler says that this isn't correct, buy I don't really get why. 我的编译器说这是不正确的,买我真的不明白为什么。
On the same topic: 在同一主题上:
void function(float *&f){
// doing w/e here
}
then in the main function: 然后在主要功能:
float *v;
function(v+5);
This is also incorrect for some reason, which I don't get either. 由于某些原因,这也是不正确的,我也没有。
So my question is: Why are those calls incorrect? 所以我的问题是:为什么这些呼叫不正确?
The first example isn't correct because &v
is a pointer to a float. 第一个示例是不正确的,因为&v
是指向浮点数的指针。 The function is expecting a reference to a double. 该函数期望引用双精度型。 A pointer to a float is not a reference to a double. 指向浮点数的指针不是对double的引用。 They are incompatible types. 它们是不兼容的类型。
The second example isn't correct because v+5
is temporary. 第二个示例是不正确的,因为v+5
是临时的。 You can't pass a reference to a non-const temporary. 您不能传递对非const临时文件的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.