简体   繁体   English

如何在链接列表中重载operator ++

[英]how to overload operator++ in linked list

Help me, please, realize overload operator++ in doubly linked list. 请帮助我,在双链表中实现重载运算符++。 I have a two classes A and B. 我有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;
    }
}

After execution method incValue() head = NULL I don't understand why this don't work. 执行方法incValue()head = NULL后,我不明白为什么这不起作用。

PS This code must be eq. PS此代码必须为eq。 head++ 头++

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

To overload operator ++ you need to support some data member of the linked list that will define the current position in the list. 要使运算符++重载,您需要支持链表的某些数据成员,这些成员将定义链表中的当前位置。 Also you need a member function that will reset the current position in the linked list. 另外,您需要一个成员函数,该函数将重置链表中的当前位置。

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

First. 第一。 You overloading operator to use first parameter as a class -> you don't need to make operator friend. 您可以重载运算符以将第一个参数用作类->无需让运算符成为朋友。

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

This overloaded operator will work with object of class A. So to use it just write: 此重载运算符将与A类的对象一起使用。因此,只需编写以下代码即可使用:

A a;
a++;

And realization of this operator will be: 该运算符的实现将是:

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

You realization will work only like: 您的认识只会像这样:

A a;
a = a++;

Because operator ++ return new copy of A object, but incremented h and a members. 因为运算符++返回A对象的新副本,但增加了h和一个成员。

Second. 第二。 About walking in list: Your while will stop when head == NULL, so after execution while loop head pointer will be equal to 0. So, that loop statement head++ will be executed for every object. 关于进入列表:您的while将在head == NULL时停止,因此执行后while循环头指针将等于0。因此,将对每个对象执行该循环语句head++

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM