为什么我不能传递地址作为参考?
我有一个函数将指针作为引用参数,但我无法将 &my_variable
传递给该函数。我收到的错误是使用 VS2010 无法将参数从 my_class* 转换为 my_class*&。
为什么这是不允许的?
class my_class
{
public:
my_class();
my_class(my_class* &parent);
};
--
int main()
{
my_class a;
my_class b(&a); // Not legal
// ---
my_class a;
my_class* a_ptr = &a;
my_class b(a); // Legal
// ---
my_class* a = new my_class;
my_class* b = new my_class(a); // Legal
}
I have a function that takes a pointer as a reference argument, but I cannot pass in &my_variable
to the function. The error I am receiving is cannot convert parameter from my_class* to my_class*&
, using VS2010.
Why is this not allowed?
class my_class
{
public:
my_class();
my_class(my_class* &parent);
};
--
int main()
{
my_class a;
my_class b(&a); // Not legal
// ---
my_class a;
my_class* a_ptr = &a;
my_class b(a); // Legal
// ---
my_class* a = new my_class;
my_class* b = new my_class(a); // Legal
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
地址表达式的结果是右值。因此,您不能将其绑定到非常量引用。
这也是没有意义的。这就像说
int a; &a = 12;
显然你不能改变变量a
的地址。相反,您需要这样:
如果函数不需要改变指针,则通过常量引用或值传递它。
The result of an address-of expression is an rvalue. Therefore, you cannot bind it to reference-to-nonconst.
It also makes no sense. It's like saying
int a; &a = 12;
Obviously you cannot change the address of the variablea
.Instead, you want this:
If the function does not need to mutate the pointer, pass it either by const-reference or by value.
当你写下这样的内容时,请考虑一下情况
Think about situation when you write something like
非正式地,期望通过引用传递参数的方法期望它传递可以合法放置在赋值语句左侧的内容(有时称为“左值”)。
在这种情况下,值得指出的是,在大多数情况下,按值传递指针成本低廉并且可行。如果您确实需要可修改指针(通过引用传递),那么您需要传递左值。
另一种选择是让引用为 const。那么我相信你可以很好地传递
rvalues
。Informally, a method expecting a parameter by reference expects that it gets passed something that can be legally placed on the left side of an assignment statement (sometimes called an "lvalue").
In this case, it's worth pointing out that in most cases, passing a pointer by value is inexpensive and will work. If you really need the pointer to be modifiable (passed by reference), then you need to pass an lvalue.
Another option is to have the reference be
const
. Then I believe you can passrvalues
just fine.