2015-03-27 3 views
1

Я пытаюсь объединить два объекта вместе, даже если они содержат одни и те же переменные. Я делаю это путем перегрузки operator +=, но мне не удается вернуть вновь созданный объект temp, созданный внутри функции unionOfBag. Я получаю только одно значение obj по умолчанию, но не дополнение.Добавление двух объектов вместе в C++

CLASS FILE:

#pragma once 
#include "BagInterface.h" 
#include <iostream> 
#include <vector> 
using namespace std; 


static const int DEFAULT_CAPACITY = 20; 

template <class ItemType> 
class ArrayBag : public BagInterface<ItemType> { 

private: 

    //ItemType *aptr; 
    ItemType items[DEFAULT_CAPACITY]; 
    int itemCount; 
    int maxItems; 

    int getIndexOf(const ItemType &target, int searchIndex) const; 
    int countFrequency(const ItemType &target, int searchIndex) const; 

public: 
    ArrayBag(); 
    //ArrayBag(const ArrayBag<ItemType> &aBag); 
    int getCurrentSize() const; 
    bool isEmpty() const; 
    bool add(const ItemType &newEntry); 
    bool remove(const ItemType &newEntry); 
    void clear(); 
    bool contains(const ItemType &anEntry) const; 
    int getFrequencyOf(const ItemType & anEntry) const; 
    vector<ItemType>toVector() const; 

    ArrayBag<ItemType> &unionOfBags(const ArrayBag<ItemType> &aBag) const; 
    ArrayBag<ItemType> intersectionOfBags(const ArrayBag<ItemType> &aBag) const; 
    ArrayBag<ItemType> differenceOfBags(const ArrayBag<ItemType> &aBag) const; 

    ArrayBag<ItemType> &operator += (const ArrayBag<ItemType> &aBag); 
    ItemType &operator [] (int subs); 
}; 


template <class ItemType> 
ArrayBag<ItemType>::ArrayBag() { 

    itemCount = 0; 
    maxItems = DEFAULT_CAPACITY; 
} 

//template <class ItemType> 
//ArrayBag<ItemType>::ArrayBag(const ArrayBag<ItemType> &aBag) { 
// 
// this->items = aBag.items; 
// this->itemCount = DEFAULT_CAPACITY; 
// 
//} 

template <class ItemType> 
bool ArrayBag<ItemType>::add(const ItemType &newEntry) { 

    bool hasRoomToAdd = (itemCount < maxItems); 

    if (hasRoomToAdd) { 
     items[itemCount] = newEntry; 
     itemCount++; 
    } 

    return hasRoomToAdd; 
} 

template <class ItemType> 
vector<ItemType> ArrayBag<ItemType>::toVector() const { 

    vector<ItemType> bagContents; 

    for (int i = 0; i < itemCount; i++) { 
     bagContents.push_back(items[i]); 

    } 

    return bagContents; 
} 

template<class ItemType> 
int ArrayBag<ItemType>::getCurrentSize() const { 

    return itemCount; 
} 

template<class ItemType> 
bool ArrayBag<ItemType>::isEmpty() const { 

    return itemCount == 0; 
} 

template <class ItemType> 
bool ArrayBag<ItemType>::contains(const ItemType &anEntry) const { 
    /*return getFrecuencyOf(target) > 0;*/ 

    bool found = false; 
    int curIndex = 0; 

    while (!found && (curIndex < itemCount)) { 
     if (anEntry == items[curIndex]) 
      found = true; 

     curIndex++; 
    } 

    return found; 
} 

template<class ItemType> 
bool ArrayBag<ItemType>::remove(const ItemType &anEntry) { 

    int locatedIndex = getIndexOf(anEntry, 0); 
    bool canRemoveItem = !isEmpty() && (locatedIndex > -1); 

    if (canRemoveItem) { 
     itemCount--; 
     items[locatedIndex] = items[itemCount]; 
    } 

    return canRemoveItem; 
} 

template <class ItemType> 
void ArrayBag<ItemType>::clear() { 

    itemCount = 0; 
} 

template <class ItemType> 
int ArrayBag <ItemType>::getIndexOf(const ItemType &target, int searchIndex) const { 

    int result = -1; 

    if (searchIndex < itemCount) { 

     if (items[searchIndex] == target) 
      result = searchIndex; 
     else 
      result = getIndexOf(target, searchIndex + 1); 
    } 


    return result; 
} 



template <class ItemType> 
int ArrayBag<ItemType>::getFrequencyOf(const ItemType &anEntry) const { 
    return countFrequency(anEntry, 0); 
} 

template <class ItemType> 
int ArrayBag<ItemType>::countFrequency(const ItemType &target, int searchIndex) const { 

    int frequency = 0; 

    if (searchIndex < itemCount) { 
     if (items[searchIndex] == target) 
      frequency = 1 + countFrequency(target, searchIndex + 1); 

     else 
      frequency = countFrequency(target, searchIndex + 1); 
    } 

    return frequency; 

} 

// 
//template<class ItemType> 
//ItemType &ArrayBag<ItemType>::operator [](int subs) { 
// 
// return aptr[subs]; 
// 
//} 

template<class ItemType> 
ArrayBag<ItemType> &ArrayBag<ItemType>::operator +=(const ArrayBag<ItemType> &aBag) { 

    this->itemCount = aBag.itemCount; 

    for (int i = 0; i < aBag.itemCount; i++) { 
     this->items[i] += aBag.items[i]; 
     this->itemCount++; 
    } 
    return(*this); 
} 



template<class ItemType> 
ArrayBag<ItemType> &ArrayBag<ItemType>::unionOfBags(const ArrayBag<ItemType> &aBag) const{ 

    ArrayBag<ItemType> newBag; 

    newBag += aBag; 

    //for (int i = 0; i < aBag.getCurrentSize(); i++) { 
    // newBag.items[i] += aBag.items[i]; 
    //} 

    return newBag; 

} 
template<class ItemType> 
ArrayBag<ItemType> ArrayBag<ItemType>::intersectionOfBags(const ArrayBag<ItemType> &aBag) const { 

} 
template<class ItemType> 
ArrayBag<ItemType> ArrayBag<ItemType>::differenceOfBags(const ArrayBag<ItemType> &aBag) const { 

} 

main.cpp

#include<iostream> 
#include<string> 
#include"ArrayBag.h" 

using namespace std; 

void displayBag(ArrayBag<string> & bag){ 
    cout << "The bag contains " << bag.getCurrentSize() 
     << " items:" << endl; 
    vector<string>bagItems = bag.toVector(); 

    int numberofEntries = (int)bagItems.size(); 
    for (int i = 0; i < numberofEntries; i++) 
    { 
     cout << bagItems[i] << " "; 
    } 
    cout << endl << endl; 
} 

void bagTester(ArrayBag<string> & bag) 
{ 
    cout << "isEmpty: returns " << bag.isEmpty() 
     << "; should be 1 (true)" << endl; 
    displayBag(bag); 

    string items[] = { "one", "two", "three", "four", "five", "one" }; 
    cout << "Add 6 items to the bag: " << endl; 
    for (int i = 0; i < 6; i++) 
    { 
     bag.add(items[i]); 
    } 
    displayBag(bag); 

    cout << "isEmpty: returns " << bag.isEmpty() 
     << "; should be o (false)" << endl; 
    cout << "getCurrentSize: returns " << bag.getCurrentSize() 
     << "; should be 6" << endl; 
    cout << "Try to add another entry: add(\"extra\") returns " 
     << bag.add("extra") << endl; 
} 

int main() 
{ 
    ArrayBag<string> bag1; 
    ArrayBag<string> bag2; 
    ArrayBag<string> newBag; 

    bag2.add("a"); 
    bag2.add("b"); 
    bag2.add("c"); 
    bag2.add("d"); 
    bagTester(bag1); 

    bag1.unionOfBags(bag2); 
    newBag = bag1; 
    displayBag(newBag); 

    cout << "All done!" << endl; 

    return 0; 
} 
+0

Вы хотите, чтобы ваш оператор '+ =' добавлял отдельные элементы вместе или добавлял два массива? Ваша текущая реализация, похоже, пытается сделать то же самое и не делать ни правильно, ни правильно. – IronMensan

+0

Im пытается добавить два массива. Как получить все предметы из объекта один и объект два и добавить их к новому объекту. Пример объекта 1 содержит один, два, три, четыре и т. Д., А объект 2 содержит a, b, c, d, чтобы добавить их toegther для создания объекта с одним, двумя, тремя, четырьмя ... a, b, c, d. – Silvestrini

ответ

2

Вы возвращаете локально созданный объект по ссылке. Это БОЛЬШОЙ нет. Когда функция заканчивается, все локальные объекты уничтожаются. Поскольку вы вернули ссылку с объекта, который был уничтожен, на что ссылается эта ссылка?

Если вы хотите вернуть объект, являющийся локальной переменной, вам нужно будет вернуть его по значению.

+0

Хорошо, я понимаю, что вы имеете в виду. Но должно ли это быть как в unionOfBag, так и в операторе + = функции? – Silvestrini

+0

+ = должен возвращать ссылку на левый объект, чтобы сделать что-то вроде следующего: '(left + = right) .someFunction (...)'. В unionOfBags вы не меняете ни левого, ни правого, поэтому вы должны вернуть вновь созданный ArrayBag, но не по ссылке, а по значению, чтобы ваш временный объект был скопирован из функции в объект вне функции. – Databyte

Смежные вопросы