2015-06-06 78 views
-2

我讀了關於多態性的時間分配,但當我們使用它時仍然感到困惑。我試着理解這個例子,但每個例子看起來都是一樣的,我只是想問一下,當BASE & Derived具有相同的功能和對象正在使用指針?當對象聲明爲指針時,我們使用多態嗎?

+1

在[cplusplus.com](http://www.cplusplus.com/doc/tutorial/polymorphism/)資源中有很好的解釋。 –

+0

@RawN讓我再次奮鬥。但是,你能回答我們,當我們將對象聲明爲指針時,我們使用它嗎? – UnKnown

+0

您需要一個指針或引用來利用多態。對象本身如何聲明並不重要。實際上,這也顯示在Raw N('Rectangle rect; Polygon * p = ▭')鏈接的示例中。 – user463035818

回答

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; 
}