The reason you're getting compiler errors is this line:
T this_array[start_size];
This line would make your Tarray
actually contain start_size
instances of T
. It wouldn't hold a pointer or reference to these instances - they would be part of same block of memory that contains the Tarray's other instance variables.
This would make the class' size depend on start_size, and start_size is not known at compile time. The size of any C++ class must be known at compile time, this isn't possible.
There are two ways to solve this:
- Allocate the array of
T
instances on the heap, using array new. This is what std::vector
does. Writing such a class and getting it to behave right when it's copied/moved/expanded/etc is difficult and tedious, so I'd recommend just using std::vector
instead.
- Make the number of T instances fixed, and pass it as a template parameter
i.e.:
template<typename T, std::size_t N>
class TArray
{
...
T this_array[N];
...
}
This is what std::array (C++11 only) and boost::array do. Again, I'd recommend using one of these instead of writing your own. Unless this is homework, of course...
Lastly, it's worth noting that this is an error:
~Tarray(){
delete[] this_array;
}
this_array
wasn't allocated with new
, so you shouldn't delete
it. If the array is part of the class as it is here (rather than being separately heap-allocated and owned by the class), then it will be destroyed along with the rest of the class by default. Calling delete
is not only unnecessary, it will almost certainly cause a crash.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…