首页 > 解决方案 > 二进制“[”:未找到采用 const Stack 类型的左操作数的运算符

问题描述

我已经实现了一个堆栈实现(使用单链表,也由我实现),当试图重载“<<”运算符以进行显示时,我遇到了这个问题。

这是我的堆栈:

template <class T>
class Stack
{
    public:
        LinkedList<T> stack;
        int Length;

        Stack() {
            Length = 0;
        }

        void Push(const T value) {
            stack.Add(value);
            Length = stack.Length;
        }

        T Pop() {
            T value = stack[0];
            stack.Delete(0);
            Length = stack.Length;
            return value;
        }

        T operator[](const int index) {
            return stack[index];
        }

        friend std::ostream& operator <<(std::ostream& os, const Stack<T>& s) { //const here causes error
            for (int i = 0; i < s.Length; i++)
                os << s[i] << " ";
            return os;
        }
};

索引运算符[]工作正常我在 main 中运行以下代码来测试堆栈:

Stack<int> stack;
stack.Push(10);
stack.Push(5);
stack.Push(11);
std::cout << stack[1] << std::endl; // prints 5 as expected

但是,当尝试使用std::cout << stack;它打印堆栈的全部内容时,会出现标题中提到的错误。从运算符重载中删除关键字修复了这个问题,但据我所知,传递不应该在没有关键字const的情况下可变的对象并不是一个好习惯。const

如何在不删除const关键字的情况下使代码工作?

标签: c++operator-overloading

解决方案


operator[]是非常量的,这就是编译器抱怨的原因。

您可以添加const重载以使 i 工作:

T operator[](const int index) const {
    return stack[index];
}

推荐阅读