【问题标题】:Linked List Front() function syntax error链表 Front() 函数语法错误
【发布时间】:2013-05-07 20:47:38
【问题描述】:

我试图在我的链表类的 Front() 方法中返回一个节点。 front 方法只返回链表中的第一个元素(即,它是一个节点)。然而,编译器不喜欢这样。它给了我以下错误。

Error: initial reference value of reference to non-const must be an lvalue.

有没有人知道解决这个问题的方法? mHead 是智能感知下划线的内容。

Node &List::Front()
{
return mHead->getData();
}

Potion Node::getData()
{
return mData;
}

list.h

#ifndef LIST_H
#define LIST_H

#include "node.h"
#include "potion.h"

class List
{

public:
//Default constructor
List();

//Copy constructor
List(const List & copy);

//Overloaded assignment operator
List &operator=(const List & rhs);

//Destructor
~List();

//Methods
void PushFront(Node * newNode);
void PushBack(Node * newNode);
void PopFront();
void PopBack();
/*const Potion &Front() const;
const Potion &Back() const;*/
Node &Front();
Node &Back();
void Purge();
bool empty();
int getNumberOfNodes();
Node * CreateNode(Potion potion);
void Save(std::ofstream & file);
void Load(std::ifstream & file);

protected:
//Data members
Node * mHead;
Node * mTail;
static int mNumberOfNodes;
};

#endif

【问题讨论】:

  • 不应该是return *mHead;吗?您想返回 Node 而不是 Potion
  • @JesseGood 非常感谢!

标签: c++ linked-list


【解决方案1】:

我猜你的getData() 函数返回的是数据的副本而不是引用。临时对象不是lvalue

【讨论】:

  • 我只是将其更改为通过引用返回,现在它说的是error: a reference of type "Node &" (not const-qualified) cannot be initialized with a value type of Potion
  • @MrPickle5,您的签名说您要返回Node&,但您正试图返回Potion&。您需要选择其中一个并保持一致。
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 2014-11-26
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2014-12-31
相关资源
最近更新 更多