我正在尝试用 C++ 编写动态数组模板
我目前正在重载 [] 运算符,并且我想根据它们在赋值的哪一侧使用来实现不同的行为。
#include <iostream>
...
template <class T>
T dynamic_array<T>::operator[](int idx) {
return this->array[idx];
}
template <class T>
T& dynamic_array<T>::operator[](int idx) {
return this->array[idx];
}
using namespace std;
int main() {
dynamic_array<int>* temp = new dynamic_array<int>();
// Uses the T& type since we are explicitly
// trying to modify the stored object
(*temp)[0] = 1;
// Uses the T type since nothing in the array
// should be modified outside the array
int& b = (*temp)[0];
// For instance...
b = 4;
cout<<(*temp)[0]; // Should still be 1
return 0;
}
由于显而易见的原因,当尝试像这样重载时,我会遇到编译器错误。
有没有正确的方法来做到这一点?
到目前为止我的搜索还没有成功。我所看到的任何重载的 [] 运算符似乎都接受用户可以修改对象外部的存储项。
我已经实现了使用 (instance(int i), update(int i, T obj)) 的方法,但如果能够像常规数组一样使用此类,那就太好了。
您不能仅重载返回类型。
提供恒定和非常量访问器重载的标准方法是通过常量来区分this
:
T & get() { return x; }
const T & get() const { return x; } // or T get() const;
对于常量版本,您可以返回常量引用或按值返回,具体取决于什么T
is - const-reference 可能更普遍有用。
(代替get()
你会写operator[](std::size_t i)
, 当然。我只是想保持简短。)
我认为这并不能 100% 达到你的想法,但那是因为你的推理有错误:int b = foo()
will never可以引用任何事物,即使foo()
返回一个(常量或非常量)引用,因为b
被声明为类型int
, not int&
。实际上,当你说时,你实际上会调用非常量版本int b = (*temp)[0];
但这实际上不是问题。 (要获得恒定版本,你必须说int b = static_cast<const dynamic_array<int> &>(*temp)[0];
or (*static_cast<const dynamic_array<int> *>(temp))[0]
- 但何苦呢。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)