c++ - 运算符 [][] 重载

标签 c++ operator-overloading

是否可以重载 [] 运算符两次?允许这样的事情:function[3][3](就像在二维数组中一样)。

如果可能的话,我想看看一些示例代码。

最佳答案

您可以重载 operator[] 以返回一个对象,您可以在该对象上再次使用 operator[] 以获得结果。

class ArrayOfArrays {
public:
    ArrayOfArrays() {
        _arrayofarrays = new int*[10];
        for(int i = 0; i < 10; ++i)
            _arrayofarrays[i] = new int[10];
    }

    class Proxy {
    public:
        Proxy(int* _array) : _array(_array) { }

        int operator[](int index) {
            return _array[index];
        }
    private:
        int* _array;
    };

    Proxy operator[](int index) {
        return Proxy(_arrayofarrays[index]);
    }

private:
    int** _arrayofarrays;
};

然后你可以像这样使用它:

ArrayOfArrays aoa;
aoa[3][5];

这只是一个简单的例子,你想添加一堆边界检查和东西,但你明白了。

关于c++ - 运算符 [][] 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66255547/

相关文章:

c++ - 如果实际对象是非常量,const_cast(this) 是否具有写操作未定义行为?

c++ - 通过 Gnuplot 的管道接口(interface)从 C/C++ 可视化

c++ - 指针为什么不存储和打印与应该匹配的对象相同的数据? (C++)

c++ - 使用空格键和回车键在 cin 中输入值之间的区别?

c++ - 使用自定义类的 C++ STL 映射的运算符重载

c++运算符在模板类中重载

c++ - 使用自定义转换运算符向上转换到模板类

C++风格的构造函数调用

c++ - 我应该在我的 C++ WIn32 应用程序中重写 operators new/delete

c++ - 为什么 cout << 不能与重载的 * 运算符一起工作?