C++ 传递对象地址时“地址表达式必须是左值或函数指示符”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10516554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Address expression must be an lvalue or a function designator" when passing an object's address
提问by Reck Hou
Here is part of my code:
这是我的代码的一部分:
class A
{
public:
void init(classB& pObject);
classB& _pObject;
}
void classA::init(classB& pObject)
{
_pObject = pObject;
}
class B
{
public:
void init();
}
void classB::init()
{
classA* pClassA = new classA;
pClassA->init(&this);
}
I got 2 problems after compile:
编译后我遇到了两个问题:
_pObject = pObject;
: No viable overloaded '='pClassA->init(&this);
: Address expression must be an lvalue or a function designator
_pObject = pObject;
: 没有可行的重载 '='pClassA->init(&this);
: 地址表达式必须是左值或函数指示符
I'm getting confused about these problems... How can I fix that?
我对这些问题感到困惑......我该如何解决?
采纳答案by Gorpik
First, there is a typo in the question. I assume that A
and classA
refer to the same class, ditto for B
and classB
.
首先,问题中有一个错字。我假设A
并classA
指的是同一个类,同理B
和classB
。
1) One of the few differences between a reference and a pointer is that you cannot assign a different value to a reference once it's been initialised. So you just cannot assign to _pObject
, though you can initialise it in the initialisation list of the constructor for class A
:
1) 引用和指针之间的少数区别之一是,一旦引用被初始化,就不能为其分配不同的值。所以你不能分配给_pObject
,尽管你可以在类的构造函数的初始化列表中初始化它A
:
classA::classA(classB& object) : _pObject(object) // Correct
{
// _pObject = object; on the other hand, this would be incorrect
}
2) &this
is the address of this
, but you actually want a reference to the value pointed to by this
. You need to use *this
instead. Though we have already seen that there is no way to make function classA::init
work with your current class design. If you really want to change the value of _pObject
after the object has been constructed, you need to make it a classB*
instead of a classB&
.
2)&this
是 的地址this
,但您实际上想要对 指向的值的引用this
。你需要*this
改用。尽管我们已经看到没有办法让函数classA::init
与您当前的类设计一起工作。如果您真的想_pObject
在对象被构造后更改 的值,则需要将其设为 aclassB*
而不是 a classB&
。
回答by Alexander Poluektov
1) You should use *this
in this context, as &this
has the type of ClassB**
, not ClassB&
;
1) 您应该*this
在此上下文中使用,&this
的类型ClassB**
,而不是ClassB&
;
2) You can only initialize you reference member-variables in constructor:
2)您只能在构造函数中初始化您引用的成员变量:
classA::classA(classB& b) : _pObject(b)
{
}
(BTW I suppose that you ommitted delete
statement just for brevity)
(顺便说一句,我想您delete
只是为了简洁而省略了陈述)