STL的函數參數類型很規範而且很有效率,舉個例子說明
const T& getTop() const
cosnt T&指的是getTop()返回的是引用,減少一次值返回構造的臨時對象,但是這個對象又是不可更改的(和T &operator=()對比),同時這是一個const函數,表示不會修改類的成員變數!
具體的實現代碼:
class Stack
{
public:
Stack():max_size(init_size)
{
top=base=(T*)malloc(sizeof(T)*init_size);
}
~Stack()
{
delete base;
}
void pushStack(const T &elem)
{
if ( (top-base)/sizeof(T*) > max_size-1)
{
handleOverflow();
}
else
{
*top=elem;
top++;
}
}
void popStack()
{
if (isEmpty())
{
return;
}
else
{
top--;
}
}
const T& getTop() const
{
if (isEmpty())
{
return NULL;
}
return *(top-1);
}
bool isEmpty()
const
{
if (top==base)
{
return true;
}
return false;
}
private:
static const int init_size=100;
unsigned int max_size;
T *top, *base;
void handleOverflow()
{
unsigned int pre_size=max_size;
T* pre_base=base;
max_size*=2;
base=(T*)malloc(sizeof(T)*max_size);
memcpy(base, pre_base, pre_size*sizeof(T));
delete pre_base;
pre_base=NULL;
top=base+pre_size;
}
};