简体   繁体   中英

Overload array subscript operator

Is there any way to overload the array subscript operator in C++ other than in a class? I would like to call a user-defined function when reading/writing in the array.

For example:

int* array = new int[10];
array[0] = 5;

When writing in array[0], I would like to call my own function. I know it can be done inside a class by overloading the operator[] (for example, a SafeArray class).

Thanks.

What you want is a wrapper class, something like:

template<typename T>
struct SubscriptWrapper {
    SubscriptWrapper(T* array) : array_(array) {};
    T& operator[](size_t index) { 
        // your magic goes in here
    };
    T* array_;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM