Vector and []-operator overloading

前端 未结 3 1285
一向
一向 2020-12-21 15:56

I have inherited my class from std::vector. Now I want to overload the []-operator.
When I try to assign a new value to my vector, e.g. v[0]=5, I should rec

3条回答
  •  一整个雨季
    2020-12-21 16:56

    This particular error is caused because you are not returning an lvalue, generally defined as something that can appear to the left of an assignment, such as v[0] = 5;. You have more problems as pointed out in the other answers but this is the specific issue you face with that error message (a).

    The correct specification for overloading the index operator is:

    int& operator[] (const int nIndex);
    

    You have to return a reference to the item (so it can be modified) if you want to treat it as an lvalue. The following code shows a fix, although obviously all array indexes map to the same value in this simplified case:

    #include 
    #include 
    
    class Vec : public std::vector {
        public:
            int& operator[] (int);    // <-- note the '&'
        private:
            int xyzzy;
    };
    
    int& Vec::operator[] (int idx) {  // <-- note the '&'
        std::cout << "OK\n";
        return xyzzy;
    }
    
    int main () {
        Vec v;
        v[0] = 5;
        v[1] = 6;
        std::cout << v[22] << '\n';
        return 0;
    }
    

    The output of this is:

    OK
    OK
    OK
    6
    

    In reality, you wouldn't map all indexes to the same value, the code above is simply to illustrate the correct function signature. I haven't bothered to give a more complete example since subclassing classes with non-virtual destructors regularly leads to problems in non-trivial code (b).


    (a) It's not usually considered a good idea to subclass std::vector since the destructor isn't virtual, so you can get into trouble when trying to destroy an object polymorphically.

    You're probably better off using a has-a relationship (where your class contains a vector) rather than an is-a relationship (where you inherit).

    That unfortunately means you may have to create a lot of pass-through methods from your class to the underlying vector (although only the ones you need) but it will solve the problem with the destructor.


    (b) See (a) :-)

提交回复
热议问题