簡體   English   中英

C++ 重載 += 用於合並兩個返回類型為 void 的包

[英]C++ Overloading += for union of two bags with return type of void

我正在嘗試為我的名為 Bag 的 class 重載 += function (聯合)。 返回類型是 void,所以我不能返回一個新數組,這是我最初的想法。 知道了這一點,我嘗試簡單地將新數組復制到一個向量中,如下面的代碼所示。 填充 bag1 和 bag2 后,我使用了重載的 function += 似乎有效。 然后我展示了 bag1,我認為它包含兩個包的並集,但它只包含原始包。

我是否錯過了一些重要的事情,比如不理解 toVector() function?

對於冗長的代碼,我深表歉意,但我不確定是否需要省略與此問題相關的部分不必要代碼。

我還嘗試填充第三個袋子 bag3 以包含 bag1 += bag2。 但我認為我需要重載 = function 才能做到這一點。

#include <iostream>
#include <string>

#include <vector>
using namespace std;

template<class T>
class Bag
{
public:
    Bag();
    int getCurrentSize() const;
    bool isEmpty() const;
    bool add(const T& new_entry);
    bool remove(const T& an_entry);
    /**
     @post item_count_ == 0
     **/
    void clear();
    /**
     @return true if an_etry is found in items_, false otherwise
     **/
    bool contains(const T& an_entry) const;

    /**
     @return the number of times an_entry is found in items_
     **/
    int getFrequencyOf(const T& an_entry) const;

    /**
     @return a vector having the same cotntents as items_
     **/
    std::vector<T> toVector() const;

    void display() const;  // displays the output 

    void operator+=(const Bag<T>& a_bag); //Union

protected:
    static const int DEFAULT_CAPACITY = 200;  //max size of items_
    T items_[DEFAULT_CAPACITY];              // Array of bag items
    int item_count_;                         // Current count of bag items
    int getIndexOf(const T& target) const;


};
template<class T>
Bag<T>::Bag(): item_count_(0)
{
}  // end default constructor

template<class T>
int Bag<T>::getCurrentSize() const
{
    return item_count_;
}  // end getCurrentSize

template<class T>
bool Bag<T>::isEmpty() const
{
    return item_count_ == 0;
}  // end isEmpty


template<class T>
bool Bag<T>::add(const T& new_entry)
{
    bool has_room = (item_count_ < DEFAULT_CAPACITY);
    //bool notDup = items_.getFrequencyOf(new_entry) == 0; 
    if (has_room) //&& notDup) 
    {
        items_[item_count_] = new_entry;
        item_count_++;
        return true;
    }  // end if

    return false;
}  // end add

template<class T>
void Bag<T>::display() const {
    for(int x = 0; x < item_count_;x++)
        cout << items_[x] << ", "; 
}


/**
 @return true if an_etry was successfully removed from items_, false otherwise
 **/
template<class T>
bool Bag<T>::remove(const T& an_entry)
{
   int found_index = getIndexOf(an_entry);
    bool can_remove = !isEmpty() && (found_index > -1);
    if (can_remove)
    {
        item_count_--;
        items_[found_index] = items_[item_count_];
    }  // end if

    return can_remove;
}  // end remove


/**
 @post item_count_ == 0
 **/
template<class T>
void Bag<T>::clear()
{
    item_count_ = 0;
}  // end clear

template<class T>
int Bag<T>::getFrequencyOf(const T& an_entry) const
{
   int frequency = 0;
   int cun_index = 0;       // Current array index
   while (cun_index < item_count_)
   {
      if (items_[cun_index] == an_entry)
      {
         frequency++;
      }  // end if

      cun_index++;          // Increment to next entry
   }  // end while

   return frequency;
}  // end getFrequencyOf

template<class T>
bool Bag<T>::contains(const T& an_entry) const
{
    return getIndexOf(an_entry) > -1;
}  // end contains

template<class T>
std::vector<T> Bag<T>::toVector() const
{
   std::vector<T> bag_contents;
    for (int i = 0; i < item_count_; i++)
        bag_contents.push_back(items_[i]);

   return bag_contents;
}  // end toVector

// ********* PRIVATE METHODS **************//

template<class T>
void Bag<T>::operator+=(const Bag<T>& a_bag)
{
    Bag<T> uBag;
    for (int x = 0; x<item_count_; x++) {
        uBag.add(items_[x]);
    }

    for (int i = 0; i<a_bag.item_count_; i++) {
        uBag.add(a_bag.items_[i]);
    }
    //return uBag; // Since return type is void, I cannot do this 
    uBag.toVector(); 
}

主要的

Bag<int> bag1;
bag1.add(1);
bag1.add(2);

Bag<int> bag2;
bag2.add(3);
bag2.add(4); 

bag1.display(); //works 1,2
bag2.display(); //works 3,4

bag1+=bag2; //no errors when run without the code below 

bag1.display() // no errors, returns 1,2 which is not what I wanted 

Bag<int> bag3; 
bag3 = bag1 += bag2; //error: no match for ‘operator=’ (operand types are ‘Bag’ and ‘void’)
// I assume I need to overload the = function for this to work 

// main.cpp:9:7: note: candidate: Bag& Bag::operator=(const Bag&)
 class Bag
       ^~~~~~~~
main.cpp:9:7: note:   no known conversion for argument 1 from ‘void’ to ‘const Bag&’
main.cpp:9:7: note: candidate: Bag& Bag::operator=(Bag&&)
main.cpp:9:7: note:   no known conversion for argument 1 from ‘void’ to ‘Bag&&’

由於您的問題是關於operator += function,因此我將重點關注這一點。 以下應該有效:

template<class T>
Bag<T> & Bag<T>::operator += (const Bag<T>& a_bag)
{
    for (int i = 0; i < a_bag.item_count_; i++) {
        add(a_bag.items_[i]);
    }
    return *this;
}

按照慣例, operator +=通過添加/附加右側( a_bag )來修改左側( this )。 因此不會創建新的 object,但會返回對左側的引用,即 ( *this ),這允許=+表達式成為更大表達式的一部分,例如 function 調用中的參數。

暫無
暫無

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

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