c++ - c++ 将两个对象相加

标签 c++

我试图将两个对象相加,即使它们包含相同的变量。我通过重载 operator += 来执行此操作,但我无法设法返回在 unionOfBag 函数内创建的新临时对象。我只得到相同的默认对象,但没有添加。

类文件:

#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 {

}

主要.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;
}

最佳答案

您正在通过引用返回本地创建的对象。这是一个很大的不不。当函数结束时,所有本地对象都将被销毁。由于您从已销毁的对象返回引用,该引用指的是什么?

如果你想返回一个局部变量的对象,你需要按值返回它。

关于c++ - c++ 将两个对象相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29309247/

相关文章:

c++ - Clion 中调试和运行模式之间奇怪的不同结果

c++ - Bad Re-throw 编译但在运行时崩溃

c++ - 有没有办法将模板的替换失败转换为 bool 值(真/假)或标签(std::true_type/std::false_type)

C++ DLL 链接器错误

c++ - 从文件中读取第 n 个元素

c++ - 在客户区外绘图,winAPI

c++ - 为什么没有检测到这种缩小转换?

c++ - 具有路径重建的 Floyd–Warshall 算法找不到路径

c++ - C++ 中的 Char 数组并将其与其他合并

c++ - Windows下如何为Code::Blocks/MinGW32编译Box2D?