【发布时间】:2018-10-21 07:31:18
【问题描述】:
我目前正在学习 C++ 链表,我从教科书中点击了这段代码。我无法理解:
const string& e
我正在尝试在我的主函数中为这个类编写一些实例,以查看事情是如何工作的,但不知道如何。 例如,我想在列表中添加 3、5、7 并在列表的前面添加 1,而不是从列表中删除 7。
#include <cstdlib>
#include <iostream>
#include <string>
using std::string;
using namespace std;
class StringNode { // a node in a list of strings
private:
string elem; // element value
StringNode* next; // next item in the list
friend class StringLinkedList; // provide StringLinkedList
// access
};
class StringLinkedList { // a linked list of strings
public:
StringLinkedList(); // empty list constructor
~StringLinkedList(); // destructor
bool empty() const; // is list empty?
const string& front() const; // get front element
void addFront(const string& e); // add to front of list
void removeFront(); // remove front item list
private:
StringNode* head; // pointer to the head of list
};
StringLinkedList::StringLinkedList() // constructor
: head(NULL) { }
StringLinkedList::~StringLinkedList() // destructor
{ while (!empty()) removeFront(); }
bool StringLinkedList::empty() const // is list empty?
{ return head == NULL; }
const string& StringLinkedList::front() const // get front element
{ return head->elem; }
void StringLinkedList::addFront(const string& e) { // add to front of list
StringNode* v = new StringNode; // create new node
v->elem = e; // store data
v->next = head; // head now follows v
head = v; // v is now the head
}
void StringLinkedList::removeFront() { // remove front item
StringNode* old = head; // save current head
head = old->next; // skip over old head
delete old; // delete the old head
}
【问题讨论】:
-
const string &e是对常量(只读)字符串的引用。它用于例如void addFront(const string& e);提供对现有字符串的引用(仅可用于读取访问),而无需复制字符串(内容)本身。 (这不会阻止addFront()从e复制到v->elem。)
标签: c++ class linked-list