开发者

Assigning to a pointer returned by a function call

开发者 https://www.devze.com 2023-04-05 09:10 出处:网络
I\'m trying to implement a simple LinkedList The following开发者_运维问答 code, producing this error:

I'm trying to implement a simple LinkedList The following开发者_运维问答 code, producing this error:

error: lvalue required as left operand of assignment

The line is:

newNode->getNext() = _head;

Where getNext() returns a Node*, and i'm trying to make the new Node point at the current head before updating it. I'm probably thinking in Java and doing the transition wrong.


Since you're implementing the class, you have several options:

  1. implement a setNext(Node*) method (possibly private) and use newNode.setNext(_head);
  2. assign to the node's _next member directly: newNode._next = _head;
  3. make Node's constructors take the initial value of _next as an argument and pass _head when constructing newNode.

Since you didn't post your code, I took a guess at the name of the "next" pointer and called it _next. Also, the points 1-3 above are not mutually exclusive and are not the only possibilities.

P.S. Take a look at the C FAQ if you're unsure what "lvalue" and "rvalue" mean.


Either, dereference:

Node* Node::getNext();
*(newNode->getNext()) = _head;

(assuming _head has type Node and the assignment operator was implemented with care in Node) or, what is probably better

Node& Node::getNext();
newNode->getNext() = _head;

But anyway, this is not the way you should be doing this. You may want to implement a setter.

Also, have you considered using std::list instead of re-inventing the wheel?


You need to have the variable you are assigning to on the left hand side of the '=' sign.

_head = newNode->getNext();

After reading again, it doesn't really achieve what you want. I'd recommend implementing a "setNext" function that takes a node as an arguement, or just accessing the 'next' variable directly. newNode.next = _head; for example.


You're placing a function call on the left side, which you really can't do. Are you sure you didn't mean...

_head = newNode->getNext();
0

精彩评论

暂无评论...
验证码 换一张
取 消