This question already has answers here:
Same function with const and without - When and why?
                                
                                    (7个答案)
                                
                        
                                3年前关闭。
            
                    
我正在为数组创建一个类,使其作为堆栈工作,并且遇到了两种返回顶部元素的函数。我无法理解两者之间的区别以及编译器如何确定要调用两者中的哪一个。下面是两者的代码。

T & getTop() {                //function 1
    return arr[top - 1];
}
const T & getTop() const {   //function 2
    return arr[top - 1];


“ top”变量指向数组中的当前空单元格,T是通用数据类型。

提前谢谢你的帮助。

最佳答案

我想您的堆栈称为stack

stack<T> s;
/*do something with it*/
s.getTop(); //will call the non const version
std::as_const(s).getTop() //will call const version


并且类似地:

const stack<T> s;
s.getTop() //const version


因此,如果变量的类型不是const,它将调用非const版本。否则它将调用const版本。

10-08 08:20