Difference between creating an array in constructor and declaration in c++ -
When I was trying to create an array in C ++ class, a problem occurred while using the constructor . Here's the code:
int stacksize = 100; Int * buffer; Int StackPointer [3] = {-1, -1, -1}; Public: ThraStack (Int StackSize_U) {int buffer_u [stacksize_u * 3]; This- & gt; Buffer = buffer_u; This- & gt; Stacksx = stacksize_u; } ThraStack () {At Buffer_U [(this-> Staxes) * 3]; This- & gt; Buffer = buffer_u; }
This did not really work. When I make an array in declaration, however, it works:
int stacksize = 100; Int buffer [300]; Int StackPointer [3] = {-1, -1, -1}; Can anyone tell me what is wrong when I was using Constructor? PSS: Here is the whole class and exam program:
class threestack {int stacksize = 100; Int * buffer; Int StackPointer [3] = {-1, -1, -1}; Public: ThraStack (Int StackSize_U) {int buffer_u [stacksize_u * 3]; This- & gt; Buffer = buffer_u; This- & gt; Stacksx = stacksize_u; } ThraStack () {At Buffer_U [(this-> Staxes) * 3]; This- & gt; Buffer = buffer_u; } Balls Push (Int StackNum, Int Value); Bull pop (Intake Stacknum); Int peek (int stacknum); Bull blank (int stacknum); }; Bool Threestack :: Push (Int StackNum, Int Value) {If (StackPointer [Staccnum-1] +1 & gt; = Staxes) {cout & lt; & Lt; "Do not try to push on the full stack of plazas" & lt; & Lt; Endl; // printf ("stackpointer =% d \ n", stackpointer [stacknum-1]); Return 0; } Else {stackpointer [stacknum-1] ++; Buffer [StackPointer [StackNum-1] + (StackNum-1) * Stacksx] = Value; Return 1; }} Int threestack :: peek (int stacknum) {if (stackpointer [stacknum-1] & lt; 0) {printf (Now there is no element in stack. \ N "); return 0;} other {printf (" StackPointer =% d \ n ", StackPointer [StackName-1]; Return Buffer [StackPooiner [StackNum-1] + (StackNum-1) * Staxise];} Bull ThraStack :: Pop (Int StackNum) {If (StackPointer [StackNum-1] "hello, world! \ N "; return 0;}
compilation of C ++ arrays At the time there is a fixed size . This is the reason that your test module works - size (= 300) is known at compile time, it is mandatory because the size of an array is actually its type, which means It is that the type of int [1]
is different from int [2]
.
Still it is not known that when you "dynamically From the "Create the array in the Creator's Way" Allocating dynamic memory using the new
and delete []
operators.
Even better, try to use.
Comments
Post a Comment