【发布时间】:2023-12-07 18:08:01
【问题描述】:
当我打电话时:a7[0][1][100];
我能够获得operator[] 中的第一个索引0,但作为索引我将无法以递归方式获得其他索引值1 和100。我怎么能使用operator[] 来获得递归的以下索引值。在这个 3 维数组的例子中,operator[] 只在第一个维度 0 中被调用一次。
我的示例代码如下:
template <class T, unsigned ... RestD> struct array;
template <class T, unsigned PrimaryD>
struct array <T, PrimaryD> {
typedef T type[PrimaryD];
type data;
T& operator[] (unsigned i) {
return data[i];
}
};
template <class T, unsigned PrimaryD, unsigned ... RestD>
struct array <T, PrimaryD, RestD...> {
typedef typename array<T, RestD...>::type OneDimensionDownArrayT;
typedef OneDimensionDownArrayT type[PrimaryD];
type data;
OneDimensionDownArrayT& operator[] (int i) {
OneDimensionDownArrayT& a = data[i];
return a;
}
};
int main () {
array<int, 1, 2, 3> a7 {{{{1, 2, 3},{4, 5, 6}}}};
a7[0][1][2] = 100; //=>won't recursively go through operator[]
//I want to recursively obtain 0, 1 and 2 as index values
a7[0][1][100] = 100; //also works correctly.
std::cout << a7[0][1][100] << std::endl;
return 0;
}
【问题讨论】:
-
那么问题出在哪里?你看到了什么行为?如果它给出了编译错误,那是什么?什么是运行时行为?你的编译器和版本是什么?多一点信息也无妨,你知道的!
-
你有没有考虑过……不这样做?只需使用
operator()重载即可。真的,人们尝试方式太努力了,无法将operator[]塞入多维数组中。 -
问题在于;没有编译或运行时错误。当我调试代码时,在调用 a7[0][1][100] => 时,它只拦截索引“0”的运算符 [],并且不会将其他索引拦截为“1” '和'100'。我只是不会递归地获取我没有使用 operator() 的多维数组中的索引,因为我被限制在 operator[]/ 上实现它
-
如果你想知道调试器为什么不做你想做的事,你需要问一个关于调试器的问题。看起来程序做了你想让它做的事情。理解所涉及的语言特征没有问题。理解调试器的作用只是一个问题。我说的对吗?
标签: c++ multidimensional-array operator-overloading variadic-templates recursive-datastructures