-1

不工作

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];'

但是,替换*this[0]at(0)使其工作。我发现它*this[0]返回一个类型的对象A而不是intat(0)这样的对象非常奇怪。在这个例子中他们不应该以同样的方式工作吗?

4

1 回答 1

3

错误消息将其泄露:

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

A是从哪里来的?this是一个A* const, 从指针中获取对象的方法是取消引用 - 所以就是this[0].

你要:

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

优先级高于operator[]取消引用 - 您需要确保*this首先发生。当然,或者,您可以编写这个烂摊子:

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

但我建议使用括号。

于 2016-10-21T20:18:54.477 回答