简体   繁体   English

重载数组下标运算符

[英]Overload array subscript operator

Is there any way to overload the array subscript operator in C++ other than in a class? 除了在类中,还有什么方法可以在C ++中重载数组下标运算符? 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. 用array [0]编写时,我想调用自己的函数。 I know it can be done inside a class by overloading the operator[] (for example, a SafeArray class). 我知道可以通过重载operator [](例如,SafeArray类)在类内部完成此操作。

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_;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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