c++ - 二进制“[”:未找到采用 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
关键字的情况下使代码工作?
解决方案
你operator[]
是非常量的,这就是编译器抱怨的原因。
您可以添加const
重载以使 i 工作:
T operator[](const int index) const {
return stack[index];
}
推荐阅读
- c# - Excel CSV 编码问题
- java - 使用itext时是否可以根据页面内容添加脚注?
- mysql - 从第三个表中过滤 MySQL 复杂选择查询
- amazon-web-services - 如何从 aws lambda 函数连接到 oracle db
- c# - 在 C# 中显示 ASCII 艺术字母时的问题
- php - 如果值相同,我想合并数组
- .net - 如何在 DotNet MVC 中实现分页
- jenkins-pipeline - 如何在批处理命令中使用 Jenkins 管道中的选择参数
- android - Fabric 插件 1.26.0 不兼容
- javascript - 将事件监听器添加到 Polymer 1 中 Light DOM 上的多个元素