从std :: list <Shape*> :: iterator调用指针上的函数

MPr*_*mer 1 c++ iterator stdlist c++11

我在C++中有一个基本的多态性示例,具有以下结构.

struct Shape {
    virtual void draw() = 0;
};

struct Circle : public Shape {
    virtual void draw() {
        cout << "drawing circle" << endl;
    }
};

struct Triangle : public Shape {
    virtual void draw() {
        cout << "drawing triangle" << endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

我有一个使用此设置的函数来调用绘图函数:

void drawShapes(list<Shape*> shapes) {
    list<Shape*>::iterator pShape = shapes.begin();
    list<Shape*>::iterator pEnd = shapes.end();

    for (; pShape != pEnd; pShape++) {
        pShape->draw();
    }
}
Run Code Online (Sandbox Code Playgroud)

这正是我正在阅读的书中设置示例的方式.我尝试编译时遇到以下错误.

expression must have a pointer-to-class type
Run Code Online (Sandbox Code Playgroud)

我通过更改pShape->draw();为修复此问题(*pShape)->draw().

然后我把这个作为一个可能的错误提交给了这本书的作者,他回答了这一点

"事实并非如此,因为std :: list :: iterator有一个运算符 - >()函数,它将迭代器解析为T*(在本例中为Shape*)."

我仍然无法获得原始版本进行编译.我正在使用与VS2015捆绑在一起的编译器来进行这些测试.有谁知道为什么我可能会收到此错误?

Bar*_*rry 5

你是对的,作者错了.std::list<T>::iterator::operator*返回一个T*,这是真的.但在这种情况下,TShape*,这使得T* == Shape**.你需要取消引用一次才能得到一个Shape*.这就是为什么pShape->draw()失败,但(*pShape)->draw()有效.