C++ 为什么可以';我不能传递一个地址作为参考吗?

C++ 为什么可以';我不能传递一个地址作为参考吗?,c++,compiler-errors,C++,Compiler Errors,我有一个将指针作为引用参数的函数,但我无法将&my_变量传递给该函数。我收到的错误是无法使用VS2010将参数从我的_类*转换为我的_类*& 为什么这是不允许的 class my_class { public: my_class(); my_class(my_class* &parent); }; -- 表达式地址的结果是一个右值。因此,您不能将其绑定到对nonconst的引用 这也毫无意义。这就像说inta&a=12显然,您不能更改变量a的地址 相反,您希望这样: i

我有一个将指针作为引用参数的函数,但我无法将
&my_变量
传递给该函数。我收到的错误是
无法使用VS2010将参数从我的_类*转换为我的_类*&

为什么这是不允许的

class my_class
{
public:
    my_class();
    my_class(my_class* &parent);
};
--


表达式地址的结果是一个右值。因此,您不能将其绑定到对nonconst的引用

这也毫无意义。这就像说
inta&a=12
显然,您不能更改变量
a
的地址

相反,您希望这样:

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

如果函数不需要改变指针,则通过常量引用或值传递它。

在编写类似

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

bar b;
foo(&b);

非正式地说,通过引用期望参数的方法期望传递可以合法放置在赋值语句左侧的内容(有时称为“左值”)

在这种情况下,值得指出的是,在大多数情况下,通过值传递指针是廉价的,而且可以工作。如果确实需要指针可修改(通过引用传递),则需要传递左值

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
很好

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.
}