如果我有以下类:
class Shape {
public:
virtual float getArea(){}
};
// A Rectangle is a Shape with a specific width and height
class Rectangle : public Shape { // derived form Shape class
private:
float width;
float height;
public:
Rectangle(float wid, float heigh) {
width = wid;
height = heigh;
}
float getArea(){
return width * height;
}
};
总的来说,我调用getArea
函数如下:
int main() {
Rectangle r(2, 6); // Creating Rectangle object
Shape* shape = &r; // Referencing Shape class to Rectangle object
cout << "Calling Rectangle getArea function: " << r.getArea() << endl; // Calls Rectangle.printArea()
cout << "Calling Rectangle from shape pointer: " << shape->getArea() << endl; // Calls shape's dynamic-type's
}
我的问题是,为什么我不能解压缩指针shape
,在我的理解中,它会给出一个Rectangle
对象,我可以在它上面调用它的getArea
函数,如下所示:
cout << "Calling Rectangle from shape pointer: " << *shape.getArea() << endl
显然,HolyBlackCat
在他的评论中回答了您的问题。
但如果你对";为什么"-查看C++运算符优先级。
您会看到. -> Member access
的优先级高于*a Indirection (dereference)
。因此,除非使用括号,否则您正试图用成员访问运算符.
取消引用指针shape