Operator[] with Multiple Arguments in C
You may encounter difficulties when attempting to define an array operator in C that takes multiple arguments. Using the following syntax:
const T& operator[](const int i, const int j, const int k) const { return m_cells[k*m_resSqr+j*m_res+i]; } T& operator[](const int i, const int j, const int k) { return m_cells[k*m_resSqr+j*m_res+i]; }
You will receive an error message:
error C2804: binary operator '[' has too many parameters
Workaround (Pre-C 23)
Prior to C 23, overloading operator[] with multiple arguments was not possible. Instead, you can overload operator().
Resolution (C 23)
However, from C 23 onwards, you can overload operator[] directly. This is demonstrated in the cppreference example below:
struct V3 { double x, y, z; constexpr V3 operator[](int i) const { return { x, y, z }[i]; } // Alternatively, using std::initializer_list: friend constexpr std::initializer_list<double> operator()(const V3& v) { return { v.x, v.y, v.z }; } };
The above is the detailed content of How Can I Overload the `operator[]` with Multiple Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!