Note that there are some explanatory texts on larger screens.

plurals
  1. POTwo-Dimensional Array using Templates
    text
    copied!<p>I am trying to implement a dynamic array:</p> <pre><code>template &lt;typename Item&gt; class Array { private: Item *_array; int _size; public: Array(); Array(int size); Item&amp; operator[](int index); }; template &lt;typename Item&gt; Array&lt;Item&gt;::Array() { Array(5); } template &lt;typename Item&gt; Array&lt;Item&gt;::Array(int size) { _size = size; _array = new Item [size]; for (int i = 0; i &lt; size; i++) cout &lt;&lt; i &lt;&lt; " " &lt;&lt; _array[i] &lt;&lt; " " &lt;&lt; &amp;_array[i] &lt;&lt; endl; } template &lt;class Item&gt; Item&amp; Array&lt;Item&gt;::operator[](int index) { if (index &lt; 0 || index &gt; _size-1) cout &lt;&lt; "this: " &lt;&lt; this &lt;&lt; ". Index out of range" &lt;&lt; endl; return _array[index]; } </code></pre> <p>When used like this, it works as expected, i.e. prints <code>5</code>:</p> <pre><code>Array&lt; int &gt; testArray(5); testArray[0] = 5; cout &lt;&lt; testArray[0] &lt;&lt; endl; </code></pre> <p>However, I would like to use the class for a two-dimensional dynamic array. I thought that the following would just magically work and print 5...</p> <pre><code>Array&lt; Array&lt;int&gt; &gt; testArray(5); testArray[0][0] = 5; cout &lt;&lt; testArray[0][0] &lt;&lt; endl; </code></pre> <p>...but it does not work. It crashes when I try to set the value at [0][0]. The debugger shows me that <code>this</code> has <code>_size</code> set to 0 and <code>_array</code> to <code>NULL</code>. <code>this</code> at that point points to the first element of the <code>_array</code> of the last created Array instance. </p> <p>One of the things I don't get is when the "inner" array calls its constructor. Stepping through the code, I see that <code>Array(int size)</code> is called once and <code>Array()</code> five times. I would like to create the inner array with a specific size, but using <code>Array&lt; Array&lt;int&gt;(10) &gt; testArray(5)</code> does not compile.</p> <p>Could you provide me with some insight on this? It seems I could not quite wrap my head around templates yet...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload