I have a template class “ArrayTemp” that creates an array of pointers to type T and am trying to create a derived template that will perform numeric operations. I am having trouble implementing a operator + that will add the elements of each array and return a new array with the sums.
My template base class:
#include <iostream>
using namespace std;
template <class T>
class ArrayTemp
{
private:
T* arr;
int arrSize;
static int DSize;
public:
ArrayTemp(): arrSize(DSize), arr(new T[DSize]) {}
ArrayTemp(const ArrayTemp<T>& at): arrSize(at.arrSize), arr(new T[at.arrSize])
{
for (int i = 0; i < at.arrSize; ++i)
arr[i] = at.arr[i];
}
~ArrayTemp()
{
delete [] arr;
}
ArrayTemp<T>& operator = (const ArrayTemp<T>& source)
{
if (this != &source)
{
for (int i = 0; i < arrSize; ++i)
setElement(source.getElement(i), i);
}
return *this;
}
int getarrSize() { return arrSize; }
T& getElement(const int index) { return arr[index]; }
void setElement(const T& x, int index) { arr[index] = x; }
};
My derived template:
#pragma once
#include "ArrayTemp.h"
template <class T>
class numbers: public ArrayTemp<T>
{
public:
numbers(): ArrayTemp<T>()
{
for (int i = 0; i < (getarrSize()); ++i)
setElement(0, i);
}
numbers(const numbers<T>& n): ArrayTemp<T>(const ArrayTemp<T>& x) {}
~numbers(){}
numbers<T> operator + (const numbers<T>& n) const
{
numbers<int> arraysum;
for (int i = 0; i < getarrSize(); ++i)
arraysum.setElement((n.getElement(i) + getElement(i)), i);
return arraysum;
}
};
template <class T> int ArrayTemp<T>::DSize = 5;
So I can do something like this in main():
numbers<int> n1;
numbers<int> n2;
numbers<int> n3;
n3 = n1 + n2;
How is an overloaded operator + supposed to be implemented within a structure similar to the one I have presented above? Should I try something with a copy constructor returning the numbers object? Also, I presume since there are no new data members in the derived template, that defining an assignment operator that just calls the ArrayTemp assignment operator is sufficient?
Errors I am getting trying this method:
cannot convert 'this' pointer from 'const numbers<T>' to 'ArrayTemp<T> &'
1> with
1> [
1> T=int
1> ]
1> Conversion loses qualifiers
while compiling class template member function 'numbers<T> numbers<T>::operator +(const numbers<T> &) const'
1> with
1> [
1> T=int
1> ]
The immediate answer seems to be that you need to declare const-correct versions of your functions in the base template:
A better answer might be that you can probably safe tons of work by using an existing standard container.