c++ - 在C++中重载operator[],但要防止a[i]=one_special_specific_value

标签 c++ data-structures

我正在实现备用 vector ADT,并且想要重载运算符[]。 我有一个 int 和 double 对的列表。我想通过例如创建新节点(5, 3.5) a[5]=3.5,但我想让它不可能为其中一个节点分配 0 值,因为它应该是一个备用 vector ,所以当 a[7]=0 时,不应创建新节点。如何实现函数 double& 运算符来执行此操作?

UPD,谢谢你们,我自己做的,但你关于代理的想法正是我正在寻找的。

public:

    proxy(ListMap<T> *v, unsigned int i) : vec(v), index(i), dump(T()) { }

    ListMap<T> *vec;

    const unsigned int& index;

    T dump;

    T& operator=(T o)
    {
        if(o==0)
        {
            return dump;
        }
        return vec->operator[](index);
    }

    operator T()
    {
        return vec->operator[](index);
    }

最佳答案

表达式

a[i] = b;

涉及两个运算符:operator[]operator=

为了您的目的,您需要一个由 operator[] 返回的辅助类型,实现 operator=:

class item_helper
{
public:
    item_helper(spare_vector* vector, int index)
      : m_vector(vector), m_index(index)
    {
    }

    // Conversion operator to double.
    // Called when using as an r-value, e.g. for b = a[i]
    operator double()
    {
        return m_vector->get_item(m_index);
    }

    item_helper& operator=(double value)
    {
        // forward to the vector
        m_vector->set_item(m_index, value);
        return *this;
    }

private:
    spare_vector* m_vector;
    int m_index;
};

class spare_vector
{
public:
    // Instead of a double, we return an item_helper, that can be
    // converted to double, and invokes special logic when assigned
    // a double.
    item_helper operator[](int index)
    {
        return item_helper(this, index);
    }

    double get(int index)
    {
        // return a value by index
    }

    void set_item(int index, double value)
    {
        // create your new node, handle the special case if "value" is zero
    }
};

如果您想隐藏 get_itemset_item 方法,请将它们设为私有(private),并将 item_helper 设为 spare_vector< 的友元.

关于c++ - 在C++中重载operator[],但要防止a[i]=one_special_specific_value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20105097/

相关文章:

c++ - 非虚拟多重继承示例

java - 在单向链表中添加双向链表节点

language-agnostic - 列表字典有更正式的术语或名称吗?

c++ - 如何创建一个 "event"系统来接收数据包

调用构造函数时出现 C++ 链接器错误(初学者 :-()

java - 排序 vector - AddItem

java - 二 fork 树的最左节点和最右节点是什么?

algorithm - 子图算法

c++ - 如何展开模板特化

c++ - 将 1Byte 数据转换为 4Byte 时详细发生了什么