1

I am trying to implement own set in C++ using class templates and operators overriding.

I have following code in my MySet.h file:

#include "stdafx.h"
#pragma once
#include <iostream>
#include <string>
using namespace std;
#define DEFAULT_LEN 10

template <class T> class MySet
{
public:
    MySet(int len = DEFAULT_LEN)
    {
        elements = new T[len];
        count = 0;
    }

    ~MySet()
    {
        delete elements;
    }

    MySet<T> operator+(T &element)
    {
        cout << "Some code here!"; //deleted to simplify code, the problem is that this method is not seen in main
        return MySet<T>();
    }

    string writeSet()
    {
        string result = "";
        for (int i = 0;i < count; i++)
        {
            result += elements[i] + ", ";
        }
        return result;
    }

private:
    T* elements;
    int count;
};

and this in my main:

#include "stdafx.h"
#include "MySet.h"

int main()
{
    MySet<int> a = MySet<int>(10);
    cout << a.writeSet();
    a = a + 2;
    a = a + 3;
    a = a + 4;
    cout << a.writeSet();
    return 0;
}

Unfortunately I am getting problems while compilling with this lines:

a = a + 2;

. The output is:

1>c:\path\main.cpp(11): error C2679: binary '+': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
1>  c:\path\myset.h(22): note: could be 'MySet<int> MySet<int>::operator +(T &)'
1>          with
1>          [
1>              T=int
1>          ]

How is this possible? As far as I understand it, MySet<T> operator+(T &element) should be enough because of T type. What am I missing?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
michalsol
  • 752
  • 8
  • 29
  • You cannot bind reference to non-const to an rvalue (`2`, `3`, `4`). Missing some `const` specifiers... After compilation, UB awaits you (double-free). – LogicStuff Jan 02 '16 at 16:22
  • You didn't even match `new []` with `delete []`, and read [this](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). – LogicStuff Jan 02 '16 at 16:24

1 Answers1

4

It has to be:

MySet<T> operator+(const T &element)
m.s.
  • 16,063
  • 7
  • 53
  • 88