当Object声明为指针时,我们使用多态性?

时间:2015-06-06 12:04:41

标签: c++ polymorphism

我读了很多关于多态的时间,但在我们使用时仍然会混淆。我试过理解这个例子,但每个例子看起来都一样,我只是想在BASE& amp;派生有相同的功能,对象用作指针吗?

1 个答案:

答案 0 :(得分:1)

想象一下这个类层次结构:

class Polygon {
    public:
        virtual double area();
        // Some other member functions
    private:
        // Some members
};

class Triangle : public Polygon {
    public:
        virtual double area() { /* code */ }
        // Some other member functions
    private:
        // Some members
};

class Square : public Polygon {
    public:
        virtual double area() { /* code */ }
        // Some other member functions
    private:
        // Some members
};

您不必使用指针,也可以使用引用。

int main(int argc, char *argv[]) {
    Triangle t;
    Square s;
    Polygon *pt = &t, *ps = &s;
    Polygon &rt = t, &rs = s;

    pt->area();         // Calls member function area from class Triangle
    ps->area();         // Calls member function area from class Square

    rt.area();          // Calls member function area from class Triangle
    rs.area();          // Calls member function area from class Square

    return 0;
}