参数通过引用传递给指针问题 [英] Argument passing by reference to pointer problem

查看:44
本文介绍了参数通过引用传递给指针问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我尝试编译我的代码时都会出错:

Every time I try to compile my code I get error:

cannot convert parameter 1 from 'int *' to 'int *&'

测试代码如下:

void set (int *&val){
   *val = 10;
}

int main(){
   int myVal;
   int *pMyVal = new int;
   set(&myVal); // <- this causes trouble
   set(pMyVal); // <- however, this doesn't
}

我想一次性调用该函数,而无需在某处创建指针只是为了传递它.由于指针没有构造函数,因此无法完成以下操作:set(int*(&myVal));

I'd like to call that function in a single shot without creating a pointer somewhere only to pass it. And as pointers don't have constructors, something like this can't be done: set(int*(&myVal));

有没有其他方法可以通过引用传递指针而无需创建临时变量?

Is there any other way to pass a pointer by reference without needing to create a temporary variable?

顺便说一下,我知道为什么代码无法编译(我只是传递可能是 int 而不是实际指针的地址).问题是还能怎么做.

By the way I know why the code fails to compile (I'm just passing the address which is possibly int and not an actual pointer). The question is how else can it be done.

推荐答案

对非常量的引用不能绑定到右值.& 运算符的结果是一个右值.看看左值和右值的区别或阅读一本好的 C++ 书籍.

A reference to non-const cannot bind to an rvalue. The result of the & operator is an rvalue. Take a look at the difference between lvalues and rvalues or read a good C++ book.

此外,在您的上下文中,您不需要通过引用传递.以下也可以:

Also, in your context, you don't need to pass by reference. The following is OK as well:

void set (int *val){
   *val = 10;
}

如果你要做这样的事情,就需要参考;

The reference would be needed if you were to do something like this;

void set (int*& val){
   val = new int; //notice, you change the value of val, not *val
   *val = 10;
}

这篇关于参数通过引用传递给指针问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆