双向链表的奇怪复制构造函数

发布于 2024-12-15 05:12:57 字数 675 浏览 1 评论 0原文

请注意我的作业标签。与所有作业一样,我们赞赏对实际编码的直接答案的有用建议。不过,请随意直接回答我的任何概念性问题。

你好,

我的教授给我们分配了一个双向链表作为家庭作业,我避免寻求帮助,直到我绝对需要它,在这里我是。

他为我们提供了头文件,然后我们必须为其创建一个类,并且必须完全遵循头文件。他的复制构造函数的方式是让我们编写一个辅助函数,我们只需要调用复制构造函数。

在正常情况下,我可以轻松做到这一点,但这次他给了我们一个非常奇怪的辅助函数签名:

// copys chain at oldHead to newHead.
static void copy(Elem *&newHead, const Elem *oldHead)

这是复制一个名为 Elems 的结构链:

struct Elem 
{
    Information info;
    Elem *next;
    Elem *back;
};

我想我最困惑的是整个函数是什么埃莱姆 *&生意,因为据我所知,不要&和 * 互相抵消吗?

谢谢,非常感谢任何和所有的帮助!希望这对将来处于我这个位置的其他人有所帮助:)

Please note my homework tag. As with all homework, helpful suggestions over straight answers to actual coding is appreciated. Feel free to answer any of my conceptual questions straight forwardly, though.

Hello,

My professor assigned us a doubly linked list for homework, and I was avoiding asking for help until I absolutely needed it, and here I am.

He provides us header files, which we then have to make a class for, and must follow the header file perfectly. The way he does his copy constructor is that he makes us write a helper function that we just have the copy constructor call.

I can do this easily, on a normal case, but this time he has given us a very bizarre signature for the helper function:

// copys chain at oldHead to newHead.
static void copy(Elem *&newHead, const Elem *oldHead)

This is to copy a chain of structs called Elems:

struct Elem 
{
    Information info;
    Elem *next;
    Elem *back;
};

I guess I'm mostly confused as to what the whole Elem *& business because, from what I remember, don't & and * cancel each other out?

Thanks, any and all help is really appreciated! Hopefully this will help other people in my position in the future:)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

潜移默化 2024-12-22 05:12:57
static Elem* copy(const Elem *oldHead)

可能是一个潜在的功能。你拿走旧的头并返回新的克隆头。

他选择的是通过引用传递指针。

如果只是

static void copy(Elem * newHead, const Elem *oldHead)
{
    newHead = new Elem();
}

像上面那样就好了。 newHead 的任何更改对于函数外部都是不可见的。

这在下面也是一样的。 x 按值传递。函数 Addten 返回后,对 x 的任何更改都会被忘记。你的 x 恰好是一个指针。

   void Addten( int x )
    {
       x = x + 10;
    }

    int x = 10;
    Addten( x );
static Elem* copy(const Elem *oldHead)

Could have been a potential function. You take the old Head and return the new cloned Head.

What he chose is passing the pointer by reference.

If it was simply

static void copy(Elem * newHead, const Elem *oldHead)
{
    newHead = new Elem();
}

something like above. Any changes to newHead is not visible to outside the function.

This is the same below. x is passed by value. Any changes to x are forgotten after the function Addten returns. Your x just happens to be a pointer.

   void Addten( int x )
    {
       x = x + 10;
    }

    int x = 10;
    Addten( x );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文