我以为我做了一些蠢事 - 至少我认为是这样.我的问题是:为什么这有效?
template<typename T>
class yarray
{
public:
yarray() {
pContainer = new T[1]; //initialize as array with size 1
unCount = 0U; //counter
}
~yarray() {
delete[] pContainer; //cleanup
pContainer = nullptr;
}
void push_back(T data)
{
((T*)pContainer)[unCount] = data; //set (shouldn't it throw an exception when unCount > 0?
unCount++; //increment
}
T operator[](const unsigned int & index)
{
if (index <= unCount)
return ((T*)pContainer)[index];
return T();
}
private:
void * pContainer;
unsigned int unCount;
};
int …Run Code Online (Sandbox Code Playgroud)