简体   繁体   中英

Use operator[] inside class that inherits std::vector

Doesn't work

class A : public std::vector<int>
{
    explicit A()
    {
        push_back(5);
        std::cout << *this[0]; 
    }
}

error: no match for 'operator*' (operand type is 'A')
std::cout << *this[0];'

Replacing *this[0] with at(0) makes it work, though. I find it very wierd that *this[0] returns an object of type A and not int , as at(0) does. Shouldn't they work the same way in this example?

The error message gives it away:

error: no match for 'operator*' (operand type is 'A')

Where does that A come from? this is an A* const , and the way to get objects from pointers is dereferencing - so that'd be this[0] .

You want:

std::cout << (*this)[0]; 

The precedence of operator[] is higher than dereference - you need to ensure that *this happens first. Of course, alternatively, you could write this mess:

std::cout << this->operator[](0);

but I'd recommend the parentheses.

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