【发布时间】:2015-07-04 01:13:58
【问题描述】:
我正在尝试用 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)) 的方法,但是能够像使用常规数组一样使用这个类会很好。
【问题讨论】: