简体   繁体   中英

C++ [ ] Index Operator Overloading As Accessor and Mutator

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
};

i need to write a template function which will do the following process:

// 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;

my code cant work with

list2[1] = 12;

i get error C2106: '=' : left operand must be l-value ERROR. i want the [] operator to be able to make list2's first index node value 12

MY CODE:

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();
    }

my code cant work with

 list2[1] = 12; 

i get error C2106: '=' : left operand must be l-value ERROR. i want the [] operator to be able to make list2's first index node value 12

In C++, we have what is known as Value Categories . You should make the operator return by reference. Hence, change your declaration from:

TYPE operator[](int);

to:

TYPE& operator[](int);

I am assuming that headcopy->getData(); equally returns a reference to a non-local variable.


As PaulMcKenzie noted, you'll equally need an overload that works with a const this , aka, const member function overload. Hence we have:

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

See What is meant with "const" at end of function declaration? and Meaning of "const" last in a C++ method declaration?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM