在 std::list<Shape*>::iterator 的指针上调用函数
Calling a function on a pointer from a std::list<Shape*>::iterator
我有一个 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;
}
};
我有一个函数使用此设置来调用绘制函数:
void drawShapes(list<Shape*> shapes) {
list<Shape*>::iterator pShape = shapes.begin();
list<Shape*>::iterator pEnd = shapes.end();
for (; pShape != pEnd; pShape++) {
pShape->draw();
}
}
这正是我正在阅读的书中示例的设置方式。当我尝试编译它时出现以下错误。
expression must have a pointer-to-class type
我通过将 pShape->draw();
更改为 (*pShape)->draw()
来解决此问题。
然后我将此作为可能的错误提交给本书的作者,他对此做出了回应
"That's not the case, actually, because std::list::iterator has an operator->() function which resolves the iterator to a T* (in this case, Shape*)."
虽然我仍然无法编译原始版本。我正在使用与 VS2015 捆绑在一起的编译器来进行这些测试。有谁知道我为什么会收到此错误?
pShape->draw();
确实应该
(*pShape)->draw();
你是对的,作者错了。 std::list<T>::iterator::operator*
returns一个T*
,这是真的。但在这种情况下,T
是 Shape*
,这使得 T* == Shape**
。您需要取消引用一次才能获得 Shape*
。这就是 pShape->draw()
失败但 (*pShape)->draw()
有效的原因。
我有一个 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;
}
};
我有一个函数使用此设置来调用绘制函数:
void drawShapes(list<Shape*> shapes) {
list<Shape*>::iterator pShape = shapes.begin();
list<Shape*>::iterator pEnd = shapes.end();
for (; pShape != pEnd; pShape++) {
pShape->draw();
}
}
这正是我正在阅读的书中示例的设置方式。当我尝试编译它时出现以下错误。
expression must have a pointer-to-class type
我通过将 pShape->draw();
更改为 (*pShape)->draw()
来解决此问题。
然后我将此作为可能的错误提交给本书的作者,他对此做出了回应
"That's not the case, actually, because std::list::iterator has an operator->() function which resolves the iterator to a T* (in this case, Shape*)."
虽然我仍然无法编译原始版本。我正在使用与 VS2015 捆绑在一起的编译器来进行这些测试。有谁知道我为什么会收到此错误?
pShape->draw();
确实应该
(*pShape)->draw();
你是对的,作者错了。 std::list<T>::iterator::operator*
returns一个T*
,这是真的。但在这种情况下,T
是 Shape*
,这使得 T* == Shape**
。您需要取消引用一次才能获得 Shape*
。这就是 pShape->draw()
失败但 (*pShape)->draw()
有效的原因。