简体   繁体   中英

Typecast generic type C++

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.

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]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM