Reputation: 2088
I overloaded the operator[]
for my DataStructure
class to return the indicated value, as follows:
T& operator[](int i) {
return m_array[i];
}
But when I loop over the values, I want to print them as follows:
for (int i = 0, s = stack->size(); i < s; ++i) {
printf("%7i %5i\n", i, stack[i]);
}
Since I created the generic DataStructure as an integer Stack (derived class)
stack = new Stack<int>(STACKSIZE);
But this does not work. I expected every item on the stack to be int, but the compiler says I cannot typecast Stack<int>
to int
, even though I'm not trying to typecast an Stack!!!
What am I missing? Also, I can not use
printf("%7i %5i\n", i, (int)stack[i]);
Since for some reason it "is not" an integer type.
Upvotes: 0
Views: 393
Reputation: 280973
If stack
is a pointer to a Stack<int>
, then stack[i]
doesn't call the stack's operator[]
. It treats the pointer as a pointer to the first element of an array and tries to index into that array. Either don't make it a pointer:
Stack<int> stack(STACKSIZE);
or dereference the pointer:
(*stack)[i]
Upvotes: 7