簡體   English   中英

用單鏈表重載 + 運算符

[英]Overloading the + operator with a single-linked list

對於我的家庭作業,我必須創建一個 int 鏈表。 我重載了復制構造函數和賦值運算符,但似乎可以重載 + 運算符。 我有一個明確的析構函數來清除列表。

List List::operator+(const List &add)
{
     List result;
     result += *this;
     result += add;
     return result;
}

+= 正在工作。 另外,當我執行以下操作時: List list3 = list1 + list2; 有用。 似乎析構函數在它返回之前就被調用了,所以如果我這樣做,我對 List3 一無所獲

List list3;    
list3 = list1 + list2;

這是復制構造函數、賦值重載和 += 重載

List& List::operator=(const List &assign)
{
    Node *traverse = assign.head;
    int x;
    int *passX = &x;
    while (traverse != nullptr)
    {
        x = traverse->getItem();
        this->Insert(passX);
        traverse = traverse->getNext();
    }
    return *this;
}

List342& List342::operator+=(const List342 &add)
{
    Node *traverse = add.head;
    int x;
    int *passX = &x;
    while (traverse != nullptr)
    {
        x = traverse->getItem();
        this->Insert(passX);
        traverse = traverse->getNext();
    }
    return *this;
}

List342::List342(const List342 &copy)
{
    *this = copy;
}

struct Node
    {
        int item;
        Node *next = nullptr;
        int getItem() const;
        Node* getNext() const;
        void setItem(const int &val);
        void setNext(Node* nodePtr);
    };
    Node *head;
    int itemCount;

最后一部分是節點的結構,以及這個類的任何對象將擁有的兩個變量。

謝謝

所以我設法弄清楚了這一點

List& List::operator+(const List &add)
{
    List *result = new List;
    *result = *this;
    *result += add;
     return result;
}

我的析構函數在返回之前清除了列表......在堆中分配空間可以防止析構函數這樣做。

感謝大家的幫助!

很好地將 operator+ 實現為 operator+= 的函數。 但是,在重載運算符 + 時,您應該同時聲明 LHS 和 RHS const。

const List List::operator+(const List &add) const
{
     List result;
     result += *this;
     result += add;
     return result;
}

第一個 const 意味着該函數返回一個 const 列表,因此您不能:

List A, B, C;
A + B = C;

第二個意味着該函數不會修改其成員變量,因此您可以相信 A+B 不會修改 A。

假設默認構造函數是一個空列表並且您的類不使用指針,請嘗試正確聲明 const。 常量變量的作用域與非常量不同。 如果您的類使用指針,請確保您實際上是在復制相關內存,而不僅僅是內存地址。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM