在C++中为链表类创建实例

Creating instances for a linked list class in C++

本文关键字:创建 实例 链表 C++      更新时间:2023-10-16

我目前正在学习链表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
}

我试图寻找一个副本来解释C++如何使用按值调用。

C++ 类型为T的函数参数将在调用函数之前创建对象的副本。

int myFunction( int value )
{
value = value + 1;
}
int main( int argc, char * argv[] )
{
int elem = 6;
myFunction( elem );
printf( "%dn", elem ); // elem = 6;
}

在上面的示例中,由int值创建副本,该值被发送到myFunction,并且副本递增。

这可能不是想要的,我们可以通过修改myFunction来引用该值,将结果更改为 7。 这是通过使用"&"来描述参考值来完成的。

int myFunction( int & value )
{
value = value + 1;
}
int main( int argc, char * argv[] )
{
int elem = 6;
myFunction( elem );
printf( "%dn", elem ); // elem = 7;
}

在上述情况下,不会创建任何副本,并且会更新 elem。

将引用传递给函数有两个主要原因

  1. 允许更新值(或对象(。
  2. 避免复制值的成本。

在您引用的示例中,第二种情况是为什么使用const string &(引用字符串对象(。std::string,有建造和破坏的成本,因此通过发送引用来避免这种情况,效率更高。

为了补充这种用法,引用通常const,以说服编译器不应更改该值。