[英]how to overload operator++ in linked list
請幫助我,在雙鏈表中實現重載運算符++。 我有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后,我不明白為什么這不起作用。
PS此代碼必須為eq。 頭++
head -> setH(head -> getH() + 1);
head -> setA(head -> getA() + 1);
要使運算符++重載,您需要支持鏈表的某些數據成員,這些成員將定義鏈表中的當前位置。 另外,您需要一個成員函數,該函數將重置鏈表中的當前位置。
如果要為A
調用重載operator++
,則需要在B::incValue
方法中調用(*head)++
。
第一。 您可以重載運算符以將第一個參數用作類->無需讓運算符成為朋友。
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和一個成員。
第二。 關於進入列表:您的while將在head == NULL時停止,因此執行后while循環頭指針將等於0。因此,將對每個對象執行該循環語句head++
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.