【问题标题】:How can I have a linked-list using class?我怎样才能有一个使用类的链表?
【发布时间】:2020-07-24 06:07:25
【问题描述】:

我正在尝试使用类编写一个链表,我希望它具有特定的格式。

例如,如果我有三个名为 p1、p2 和 p3 的数据和一个名为 list 的链表;我想把它们整理好。

list.insert(p1).insert(p2).insert(p3);

我试图返回对象,但没有成功。 这是我的代码。


#include<iostream>

using namespace std;

class linked_list {
public:
    int *head;
    linked_list();
    ~linked_list();
    linked_list  insert(int data);

};

linked_list::linked_list()
{
    head = NULL;

}
linked_list::~linked_list()
{
    int *temp;
    int *de;
    for (temp = head;temp != NULL;) {
        de = temp->next;
        delete temp;
        temp = de;
    }
    delete temp;
    //delete de;

}
linked_list  linked_list::insert(int data)
{
    int *temp;
    temp = new int;
    *temp = data;
    temp->next = NULL;
    if (head == NULL) {
        head = temp;
    }
    else {
        int* node = head;
        while (node->next != NULL) {
            node = node->next;
        }
        node->next = temp;
    //  delete node;
    }
    //delete temp;

    return *this;


}
int main(){
    linked_list l1;
    int p1,p2,p3;
    l1.insert(p1).insert(p2).insert(p3);
    return 0;}


【问题讨论】:

  • 显示的代码存在多个基本错误。不符合规则 3。引用的不当使用(没有任何使用)。您真正需要的是花更多时间with a good C++ textbook 并学习此处必须使用的基本 C++ 概念。这超出了在 stackoverflow.com 上快速回答的范围。
  • 要允许正确的list.insert(p1).insert(p2).insert(p3);,您必须返回参考。
  • int* node = head; while (node-&gt;next != NULL) {。哎哟...
  • int* 上的 next 应该从哪里来?您需要创建一个类来表示节点。

标签: c++ class pointers linked-list this


【解决方案1】:

@Jarod42 得到了你的答案,尽管周围有很多错误的东西,但你想要的是这样的东西。

您要链接的函数必须返回对当前对象实例的引用。

这是一个 Foo 类,它多次更改其 _data 成员和链。

#include <iostream>

class Foo
{
private:
    int _data;

public:
    Foo(int data) : _data(data) {}
    ~Foo()
    {
    }

    // change the value of data then return a reference to the current Foo instance
    Foo &changeData(int a)
    {
        _data = a;
        return *this;
    }

    void printData()
    {
        std::cout << _data << std::endl;
    }
};

int main()
{
    Foo f(1);

    f.changeData(2).changeData(3);
    f.printData();
}

请注意,我正在从我正在链接的函数中返回 Foo&amp;,这是你的小技巧。

希望对你有所帮助:)

【讨论】:

  • 谢谢,有用的答案,但我为什么要使用参考?当我返回对象本身时会发生什么?
  • @Lily:没有参考,你的回报..自己的副本。
猜你喜欢
  • 1970-01-01
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多