C ++堆栈实现 - top方法的两个版本

时间:2015-03-15 23:06:16

标签: c++ stack

我必须在C ++中实现两个方法

int& stack::top();
int stack::top() const;

据我所知,第一个允许我写这样的东西:

myStack->top() = 500 // now the top element is 500

我不知道第二种方法的目的是什么。

2 个答案:

答案 0 :(得分:2)

如果你这样做,第二个是有用的:

bool isTopMoreThan(const stack st, int val)
{
   return st.top() > val;
}

或者你有const堆栈对象的任何其他时间。

答案 1 :(得分:2)

末尾的const
int stack::top() const;

表示调用此函数的堆栈对象是const。当你有一个const堆栈时,你不想调用第一个函数,因为它允许非const访问堆栈的顶部元素。第一个函数末尾缺少const,确保无法在const对象上调用它。

但是你仍然希望能够至少检查堆栈顶部的值,即使它是const(或更常见的是,通过const引用访问)。这就是第二个功能。例如:

int getTop(const stack& st)
{
    return st.top();
}

如果没有第二个函数,这个(通常无用的)函数将无法编译,因为第一个函数不能在const堆栈上调用。