首页 > 解决方案 > 如何区分对数组索引的访问和分配?

问题描述

我正在编写一个动态数组类。我重载了operator[]以访问包含数组中数据的指针。在我的班级中还有一个成员size,表示数组中的对象数量。我需要能够通过分配元素来添加元素,A[i]以及使用成员函数添加到前端或末端。问题是在分配 using 时A[i] = x,我不知道要递增size。有没有办法区分 [] 运算符是否在 = 的左侧使用,而不是简单地访问该索引?我已经包含了我的实现的简化版本。

using namespace std;
#include <iostream>
class Array
{
    public:
        [constructors, destructor];
        int& operator[](int index);
        [addToFront(),addToBack(), etc.]
    private:
        int size;     // holds the number of objects in the array
        int capacity;
        int* arr;     // ptr to the data in the array
}

int& Array::operator[](int index)    // overloaded array access operator
{
    return arr[index]; // simplified version of what I use
}

int main()
{
    Array A(6);    // initialize capacity using parameterized constructor
    A.addToFront(15); // addToFront() is able to increment size inside of its function
    A[1] = 10;    // How can I know that I am adding a new object to the array
    return 0;
}

谢谢!

标签: c++operator-overloadingdynamic-arrays

解决方案


这可以通过代理对象来完成。您可以为这些对象重载 an并执行更复杂的操作,例如在该成员函数中operator =递增。size例子:

class Array
{
   // Rest as before...

   struct Proxy {
     Array& ref;
     int pos;

     Proxy& operator =(int n)
     {
        ref.arr[pos] = n;
        ++ref.size;

        return *this;
     }
   };

   Proxy operator[](int index);
};

的实施operator[]将是

Array::Proxy Array::operator[](int index)
{
   return Proxy{*this, index};
}

以及您在示例代码段中显示的用法。


推荐阅读