Vrael
Vrael

Reputation: 77

C++ Overloading operator+ in the case of a template class

I m new on c++ programing and i have to release a Set implementation for a teacher.

I have to overload operator+ as non-member function of my class Set (which should be a template class).

The problem i got is that error (at compilation): opertor+(Set, const Set&) must take either zero or one argument.

BUT my non member function IS NOT on my class Set, and so this function is supposed to take 2 parameters. I m really disapointed ...

here is my code :

#ifndef GUARD_set_h
#define GUARD_set_h

#include <iostream>
#include <array>
#include <vector>
#include <set>
#include <string>

using namespace std;
template <class T>
class Set
{
public:
    Set() {}
    Set(const T arr[], size_t arr_sz)
    {
        std::set<T> m_set;
        for(size_t i = 0; i < arr_sz; ++i)
            m_set.insert(arr[i]);

    }
    Set(const std::vector<T>& vec)
    {
        for(size_t i = 0; i < vec.size(); ++i)
            m_set.insert(vec[i]);
    }

    Set(const std::set<T>& st)
    {
        m_set = st;
    }

    Set(const Set& set_to_copy)
    {
        m_set = set_to_copy.m_set;
    }

    Set& operator +=(const Set& st) // Addition Assignement operator
    {
        for (typename std::set<T>::iterator it = st.m_set.begin(); it != st.m_set.end(); ++it)
            m_set.insert(*it);
        return *this;
    }

    private:
    std::set<T> m_set;
};

    template <class T>
    Set<T> Set<T>::operator+(Set, const Set&) // Set Union
    {

    }

#endif

Here is the error: error: 'Set Set::operator+(Set, const Set&)' must take either zero or one argument

I already ask you sorry for my approximate English, and thanks you for help :D

Upvotes: 3

Views: 215

Answers (1)

benipalj
benipalj

Reputation: 704

You need to define your non-member operator + as follows:

template <class T>
Set<T> operator+(const Set<T>& a, const Set<T>& b)
{
//implementation
}

Change your first parameter to const reference as you are creating unnecessary copy.

Upvotes: 1

Related Questions