【问题标题】:how to overload operator++ in linked list如何在链表中重载运算符 C++
【发布时间】:2013-11-17 14:20:04
【问题描述】:

请帮助我,在双向链表中实现重载运算符++。 我有 A 和 B 两个班级。

class A {
private:
    int h;
    int a;
public:
    A *next, *prev;

friend A operator ++(A &, int);
};

A operator ++(A &t, int) {
    A temp = t;
    temp.h++;
    temp.a++;
    return temp;
}


class B {
private:
    A *head, *tail;
public:
    void incValue();
};

void B::incValue() {
    while(head != nullptr) {
        head++;
        head = head -> next;
    }
}

执行后方法incValue() head = NULL 我不明白为什么这不起作用。

附:此代码必须是 eq。头++

head -> setH(head -> getH() + 1);
head -> setA(head -> getA() + 1);

【问题讨论】:

  • while(head != nullptr) 这会导致它循环直到你有head == 到nullptr (猜测)是NULL。当你把它当真时,你就打破了循环。因此,当你出来的时候 head 是 NULL
  • head 是一个数组吗?如果没有,你觉得head++ 在做什么?
  • 究竟是什么不起作用?
  • head 是列表中的第一个节点。我想让 head++ 做 head -> h = head -> h + 1
  • 从设计的角度来看,有一个类似增量的运算符或成员函数来改变链表的状态并不是很好。最好为此实现迭代器。

标签: c++ linked-list operator-overloading doubly-linked-list


【解决方案1】:

要重载运算符 ++,您需要支持链接列表的某些数据成员,这些数据成员将定义列表中的当前位置。您还需要一个成员函数来重置链表中的当前位置。

【讨论】:

    【解决方案2】:

    如果你想为A调用重载的operator++,你需要在你的B::incValue方法中调用(*head)++

    【讨论】:

      【解决方案3】:

      首先。您重载运算符以将第一个参数用作类 -> 您不需要与运算符成为朋友。

      class A {
      private:
          int h;
          int a;
      public:
          A *next;
          A *prev;
          void operator ++ ( int ); 
      };
      

      这个重载的操作符将与 A 类的对象一起使用。所以要使用它,只需编写:

      A a;
      a++;
      

      这个运算符的实现将是:

      void A::operator ++ ( int )
      {
        h++;
        a++;
      }
      

      你的实现只会像这样工作:

      A a;
      a = a++;
      

      因为运算符 ++ 返回 A 对象的新副本,但增加了 h 和 a 成员。

      第二。关于步入列表: 您的 while 将在 head == NULL 时停止,因此在执行 while 循环后,头指针将等于 0。因此,将为每个对象执行该循环语句 head++

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-23
        • 1970-01-01
        • 1970-01-01
        • 2010-12-06
        • 2011-12-03
        • 2012-06-09
        • 1970-01-01
        • 2011-05-03
        相关资源
        最近更新 更多