Home > Backend Development > C++ > How Can I Overload the `operator[]` with Multiple Arguments in C ?

How Can I Overload the `operator[]` with Multiple Arguments in C ?

Patricia Arquette
Release: 2024-11-20 02:40:02
Original
160 people have browsed it

How Can I Overload the `operator[]` with Multiple Arguments in C  ?

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];
}
Copy after login

You will receive an error message:

error C2804: binary operator '[' has too many parameters
Copy after login

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 };
    }
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template