Как построить оператор == в шаблоне класса - PullRequest
0 голосов
/ 18 марта 2020

У меня есть задание, в котором я предполагаю построить шаблон с использованием этих спецификаций.

ISet - это контейнер, в котором хранятся значения определенного порядка, где порядок не имеет значения, и который не позволяет дубликатов (или кратных). Динамически распределенный массив типа T должен использоваться в качестве внутренней структуры данных для Set . Set должен наследоваться от интерфейса ISet ниже - его нельзя изменять :

template <typename T>
class ISet
{
public:
virtual bool insert (T element) = 0;
virtual bool remove (T element) = 0;
virtual int size () const = 0;
};

• insert (T element): adds elements to the set and returns true provided that
the element is not already present in the quantity (in which case the element is not added and false is returned).

• remove (T element): removes elements from the set and returns true.
If the element is missing in the quantity, false returns.

• size (): returns the number of elements in the set.
In addition to the member functions, you must implement constructor, destructor, copy constructor
and assignment operator.

И до сих пор я подходил с этим кодом:

#pragma once
#include <string>
#include <iostream>

using namespace std;

template <class T>
class ISet
{

public:

    virtual bool insert(T element) = 0;
    virtual bool remove(T element) = 0;
    virtual int size() const = 0;
};


#pragma once
#include "ISet.h"

template <class T>
class Set : public ISet<T>
{
public:
    Set(string name);
    ~Set();
    Set(const Set &origin);
    //Set& operator=(const Set &origin);

    bool insert(T element);
    bool remove(T element);
    int size()const;

private:
    string name;
    T *arr;
    int cap, nrOfElement;
};



template<class T>
Set<T>::Set(string name)
{
    this->name = name;
    this->cap = 10;
    this->nrOfElement = 0;
    this->arr = new T[this->cap];

}

template<class T>
Set<T>::~Set()
{
    delete[] arr;
}

template<class T>
Set<T>::Set(const Set & origin)
{
    this->nrOfElement = origin.nrOfElement;
    this->cap = origin.cap;

    arr = new T*[cap];

    for (int i = 0; i < nrOfElement; i++)
    {
        arr[i] = origin.arr[i];
    }

}

template<class T>
bool Set<T>::insert(T element)
{
    bool found = false;

    if (nrOfElement == 0)
    {
        this->arr[0] = element;
        this->nrOfElement++;
    }
    else
    {
        for (int i = 0; i < this->nrOfElement; i++)
        {
            if (this->arr[i] == element)
            {
                i = this->nrOfElement;
                found = true;
            }
        }
        if (found == false)
        {
            this->arr[nrOfElement++] = element;
        }
    }

    return found;
}

template<class T>
bool Set<T>::remove(T element)
{
    bool removed = false;

    for (int i = 0; i < this->nrOfElement; i++)
    {
        if (this->arr[i] == element)
        {
            this->arr[i] = this->arr[nrOfElement];
            nrOfElement--;
            removed = true;
        }
    }
    return removed;
}

template<class T>
int Set<T>::size() const
{
    return this->nrOfElement;
}

И мои проблемы начинаются, когда я начинаю тестировать этот код, добавляя другой тип данных, с которым мы должны тестировать шаблон.

#include "Set.h"
#include "ISet.h"
#include "Runner.h"

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    Set<string> test("test");
    test.insert("lol");
    cout << test.size();
    test.remove("lol");
    cout << test.size();

    Set<Runner> test2("test");


    getchar();
    return 0;
}

Получение ошибка говорит, что «не найден оператор, который принимает левый операнд типа« Runner ». Поэтому я должен создать оператор ==, который обрабатывает это, но не знает? Класс Runner выглядит следующим образом:

* 1023» *

Как мне построить оператор ==, который будет работать для этого?

1 Ответ

1 голос
/ 18 марта 2020

Вам необходимо добавить operator== к классу Runner:

bool operator==(const Runner& other) const;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...