Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何区分对数组索引的访问和赋值?_C++_Operator Overloading_Dynamic Arrays - Fatal编程技术网

C++ 如何区分对数组索引的访问和赋值?

C++ 如何区分对数组索引的访问和赋值?,c++,operator-overloading,dynamic-arrays,C++,Operator Overloading,Dynamic Arrays,我正在编写一个动态数组类。 我重载了操作符[],以访问数组中包含数据的指针。在我的类中还有一个成员size,表示数组中对象的数量。我需要能够通过A[I]分配元素来添加元素,以及使用成员函数添加到前端或后端。问题是当使用A[i]=x分配时,我不知道如何增加大小。是否有办法区分[]运算符是否在=的左侧使用,而不是简单地访问该索引?我已经包括了我的实现的简化版本 using namespace std; #include <iostream> class Array { publi

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

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;
}
使用名称空间std;
#包括
类数组
{
公众:
[构造函数、析构函数];
int&运算符[](int索引);
[addToFront()、addToBack()等]
私人:
int size;//保存数组中的对象数
国际能力;
int*arr;//ptr到数组中的数据
}
int&Array::operator[](int index)//重载的数组访问运算符
{
return arr[index];//我使用的简化版本
}
int main()
{
数组A(6);//使用参数化构造函数初始化容量
A.addToFront(15);//addToFront()能够增加其函数内部的大小
A[1]=10;//我怎么知道我正在向数组添加一个新对象
返回0;
}

谢谢

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

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);
};
操作符[]
的实现将是

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

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

不是返回
int&
,而是返回某种重载
运算符=
的代理/包装。但我不确定这是个好主意,