C []索引操作员重载作为登录器和突变器


template <class TYPE>
class DList
{
    //Declaring private members
    private:
    unsigned int m_nodeCount;
    Node<TYPE>* m_head;
    Node<TYPE>* m_tail;
    public:
    DList();
    DList(DList<TYPE>&);
    ~DList();
    unsigned int getSize();
    void print();
    bool isEmpty() const;
    void insert(TYPE data);
    void remove(TYPE data);
    void clear();
    Node<TYPE>*  getHead();
    ...
    TYPE operator[](int); //i need this operator to both act as mutator and accessor
};

我需要编写一个模板功能,该功能将执行以下过程:

// Test [] operator - reading and modifying data
cout << "L2[1] = " << list2[1] << endl;
list2[1] = 12;
cout << "L2[1] = " << list2[1] << endl;
cout << "L2: " << list2 << endl;

我的代码无法使用

list2[1] = 12;

我获得错误C2106:'=':左操作数必须是l值错误。我希望[]运算符能够使List2的第一个索引节点值12

我的代码:

template<class TYPE>
     TYPE DList<TYPE>::operator [](int index) 
    {
        int count = 0;
        Node<TYPE>*headcopy = this->getHead();
        while(headcopy!=nullptr && count!=index)
        {
            headcopy=headcopy->getNext();
        }
        return headcopy->getData();
    }

我的代码无法使用

list2[1] = 12;

我获得错误C2106:'=':左操作数必须是l值错误。我想 []运算符能够使List2的第一个索引节点值12

在C 中,我们有所谓的价值类别。您应该通过参考使操作员返回。因此,从以下方式更改您的声明:

TYPE operator[](int);

to:

TYPE& operator[](int);

我假设headcopy->getData();平均返回对非本地变量的引用。


正如Paulmckenzie所指出的那样,您同样需要与const this(aka, const成员函数过载)配合使用的过载。因此我们有:

TYPE& operator[](int);
const TYPE& operator[](int) const;

请参阅" const"的含义。在功能声明结束时?和" const"的含义最后一个在C 方法声明中?

最新更新