双向链接列表中的成员访问 [英] Member access in a doubly-linked list

查看:67
本文介绍了双向链接列表中的成员访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正处于《编程:使用C ++的原理和实践》的第17章,我无法弄清楚。在下面的代码中,
norse_gods-> succ-> prev = norse_gods 行实际上是做什么的?我知道->是成员访问运算符,给出了指向对象的指针。这是否意味着我要访问norse_gods的前任继任者?我对此感到困惑。这只是第一部分,随后在书中定义了插入操作,该操作使用相同的符号,因此我想确切地知道它的含义。谢谢您的时间。

I'm currently at chapter 17 of Programming: Principles and Practice using C++ and I can't figure something out. In the code below, what does the line norse_gods->succ->prev = norse_gods actually do? I know that -> is a member access operator, given a pointer to an object. Does it mean that I'm accessing norse_gods successors predecessor? I'm kind of confused with that. This is only the first part, later on in the book an insert operation is defined, which uses the same notation so I'd like to know exactly what it means. Thank you for your time.

这里是代码:

struct Link {
string value;
Link* prev;
Link* succ;
Link(const string& v, Link* p = nullptr, Link* s = nullptr)
    : value(v), prev(p), succ(s) {}
};

//insert n before p (incomplete)
Link* insert(Link* p, Link*n)
{
    n->succ = p;
    p->prev->succ = n;
    n->prev = p->prev;
    p->prev = n;
    return n;
}

int main()
{
    //Building a list of Norse gods
    //                            val      prev     suc
    Link* norse_gods = new Link{ "Thor", nullptr, nullptr };
    norse_gods =       new Link{ "Odin", nullptr, norse_gods };

    norse_gods->succ->prev = norse_gods;
    norse_gods =       new Link{ "Freya", nullptr, norse_gods };

    norse_gods->succ->prev = norse_gods;


}


推荐答案

This:

Link* norse_gods = new Link{ "Thor", nullptr, nullptr };

创建一个具有NULL后继和前任的节点。现在我们在开始处附加第二个节点:

Created a node with a NULL successor and predecessor. Now we attach a second node at the beginning:

norse_gods =       new Link{ "Odin", nullptr, norse_gods };

请注意 norse_gods 中的上一个节点,作为后继附件。所以现在我们有了

Note the previous node in norse_gods, Thor, is attached as a successor. So now we have

Odin -> Thor

但是Thor的前任指针仍然为NULL!我们没有碰它!但是我们现在知道是奥丁。因此,让我们将其修复为指向当前由 norse_gods 指向的Odin:

But Thor's predecessor pointer is still NULL! We didn't touch it! But we know now it's Odin. So let's fix it to point to Odin, which is currently pointed to by norse_gods:

norse_gods->successor /*Translates to Odin's successor, which is Thor*/ ->predecessor /*This is still null from the first line*/ = /*So fix it to point to the current norse_gods, Odin*/ = norse_gods /*pointing to Odin*/

现在链接已固定,Thor的前身应该是奥丁。

So now the link is fixed, and Thor's predecessor is Odin, as it should be.

这篇关于双向链接列表中的成员访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆