C++:在另一个方法中使用预先声明的运算符[]
C++: Using predeclared operator[] in another method
我正试图在同一类的另一个方法中使用预先声明的operator[]
。但是,我不知道该怎么办。有趣的是,我甚至不知道如何在谷歌上搜索:(.请,建议…
这是一个双链接列表的一部分——我想在其中启用Array行为(我知道——不好:))。
代码片段:
template <typename T>
T& DLL<T>::operator[](int i) const{
Node <T>*n = this->head;
int counter = 0;
while (counter > i) {
n = n->next;
counter++;
}
return n->next->val;
}
template <typename T>
T& DLL<T>::at(int i) const throw (IndexOutOfBounds) {
if (i < 0 || i >= elemNum) {
throw IndexOutOfBounds("Illegal index in function at()");
}
// I want this part to use the predeclared operator
// obviously this is not right...
return this[i]; // Why u no work?!??!?
}
尝试调用this->operator[](i)
。这应该会给你带来想要的结果。
编辑
正如WhozCraig所说:(*this)[i]
同样有效,可能更优雅。
相关文章:
- 在哪里声明结构运算符重载
- 让某个类的 '=' 运算符在声明时运行构造函数
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 在一个指令中声明更多指针的运算符优先级
- 类模板中文本运算符的友元声明
- 新运算符分配的大小大于声明的大小.为什么
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?
- 为什么我不能定义一元运算符,然后在 MSVC 的模板类中声明具有相同名称的友元二进制运算符?
- 为什么重载运算符>在参数声明 const 时不起作用?
- Ho 在标头中声明是结构中的重载运算符?
- 是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
- C++ 03 类模板 这是转换构造函数还是转换运算符?以及如何声明解决此问题的方法
- 具有继承的未声明标识符(运算符 ostream)
- 我可以在工会内声明运算符吗?
- 不能在函数中声明运算符.叮当错误或规范
- 使用宏声明运算符
- 在C++中声明运算符+函数
- 如何声明运算符重载<以在需要时在类变量之间动态切换?
- 未声明运算符++后缀
- 如何为内部类声明运算符<<