When trying to build an array with a template, I get an error when implementing a default constructor for the Array class template.
int main()
{
Array<int,5> arrayOfFiveInts;
return 0;
}
template<typename T, size_t SIZE>
class Array
{
public:
Array<T,SIZE>::Array()
{
elements = new T [SIZE];
for (int i = 0; i < SIZE; i++)
{
elements[i] = 0;
}
}
private:
T elements[SIZE];
};
I am expecting to see the array created when Main runs.
You have to decide whether you want to have the array in automatic or dynamic memory.
If you meant to have it in automatic memory, you have to remove the call to new[]
in the constructor since elements
is already allocated when it is declared.
If you meant to have it in dynamic memory, you have to change the declaration of elements
to
T* elements;
If you do so, then you also need to make sure your class follows the Rule of 3/5/0 . Add a destructor:
~Array()
{
delete[] elements;
}
As well as implement (or delete) a copy/move constructor, and a copy/move assignment operator.
templates are header-only, you don't need to use the extra qualification:
Array<T,SIZE>::Array()
You have to define the class before the main()
function in your example.
Check the correct format in this Live demo .
Just remove this line
elements = new T [SIZE];
elements
is an array not a pointer, so trying to allocate some memory and assign to it doesn't make any sense.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.