C ++ []索引运算符重载为Accessor和Mutator

时间:2017-12-02 22:44:53

标签: c++ indexing operator-overloading

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:&#39; =&#39; :左操作数必须是l值ERROR。 我希望[]运算符能够使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();
    }

1 个答案:

答案 0 :(得分:1)

  

我的代码无法使用

list2[1] = 12;
     

我收到错误C2106:&#39; =&#39; :左操作数必须是l值ERROR。我想要   []运算符能够使list2的第一个索引节点值为12

在C ++中,我们拥有所谓的Value Categories。您应该通过引用使操作符返回。因此,请改变您的声明:

TYPE operator[](int);

为:

TYPE& operator[](int);

我假设headcopy->getData();同样返回对非局部变量的引用。

正如PaulMcKenzie指出的那样,您同样需要一个与const this,又称const成员函数重载一起使用的重载。因此我们有:

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

请参阅What is meant with "const" at end of function declaration?Meaning of "const" last in a C++ method declaration?