2012-01-09 70 views
4

我有一个函数,它将一个指针作为参考参数,但是我无法将&my_variable传递给函数。我收到的错误是cannot convert parameter from my_class* to my_class*&,使用VS2010。为什么我无法传递地址作为参考?

为什么不允许?

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 
} 

回答

10
表达

一地址的的结果是一个rvalue。因此,您不能将它绑定到引用到非常量。

这也没有意义。这就像是说int a; &a = 12;显然你不能改变变量a的地址。

相反,你要这样:

int a; 
int * p = &a; 
mutate_me(p); // declared as mutate_me(int * &); 

如果函数需要变异的指针,无论是常量引用或按值传递。

+0

有道理。谢谢! – Eric 2012-01-09 20:37:06

1

想想情况,当你喜欢写东西

void foo(bar*& ptr) { 
    ptr = new bar; 
} 

bar b; 
foo(&b); 
1

通俗地说,希望通过引用参数的方法希望它被传递一些可以合法地放置在赋值语句的左侧(有时也被称为一个“左值”)。

int main() 
{ 
    my_class a; 
    my_class b(&a);     // Not legal: &a = 0; would be illegal because you can't change an address of a variable. 

    // --- 
    my_class a; 
    my_class* a_ptr = &a; 
    my_class b(a_ptr);     // Legal: You've declared a_ptr on the stack and its value (what it points to) can be changed. The address of a_ptr would not be changeable though. 

    // --- 
    my_class* a = new my_class; 
    my_class* b = new my_class(a); // Legal: Again, this is on the stack and `a` could point to something else, but its own address won't be changed. 
} 

在这种情况下,这是值得指出的是,在大多数情况下,按值传递一个指针是价格低廉,将工作。如果你确实需要指针是可修改的(通过引用传递),那么你需要传递一个左值。

另一个选择是具有参考是const。那我相信你可以通过rvalues就好了。

相关问题