c++ - 如何区分对数组索引的访问和分配?
问题描述
我正在编写一个动态数组类。我重载了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;
}
谢谢!
解决方案
这可以通过代理对象来完成。您可以为这些对象重载 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};
}
以及您在示例代码段中显示的用法。
推荐阅读
- magento - 从 Observer Magento 1.9 设置产品自定义选项
- javascript - Rx.Js:理解扩展运算符
- appium - Appium Desktop 无法启动会话错误 ENOTFOUND
- python - 如何在模型中正确使用 tensorflow 函数
- spring - 如何使用自定义弹簧 DispatcherServlet 测试休息控制器
- javascript - 在 typescript svelte 中导入别名 svelte 组件
- c - C语言中,结构体包含枚举类型属性,如何将这个结构体输入并写入文件
- r - 错误在管道中找不到 r 中的函数
- java - 为什么在连接到可访问主机时在 Android 9 上引发 UnknownHostException?
- azure - Azure VM 备份/自动化在还原后不起作用