What is the real significance(use) of polymorphism

前端 未结 10 2338
别跟我提以往
别跟我提以往 2020-12-01 01:44

I am new to OOP. Though I understand what polymorphism is, but I can\'t get the real use of it. I can have functions with different name. Why should I try to implement polym

10条回答
  •  爱一瞬间的悲伤
    2020-12-01 02:08

    Classic answer: Imagine a base class Shape. It exposes a GetArea method. Imagine a Square class and a Rectangle class, and a Circle class. Instead of creating separate GetSquareArea, GetRectangleArea and GetCircleArea methods, you get to implement just one method in each of the derived classes. You don't have to know which exact subclass of Shape you use, you just call GetArea and you get your result, independent of which concrete type is it.

    Have a look at this code:

    #include 
    using namespace std;
    
    class Shape
    {
    public:
      virtual float GetArea() = 0;
    };
    
    class Rectangle : public Shape
    {
    public:
      Rectangle(float a) { this->a = a; }
      float GetArea() { return a * a; }
    private:
      float a;
    };
    
    class Circle : public Shape
    {
    public:
      Circle(float r) { this->r = r; }
      float GetArea() { return 3.14f * r * r; }
    private:
      float r;
    };
    
    int main()
    {
      Shape *a = new Circle(1.0f);
      Shape *b = new Rectangle(1.0f);
    
      cout << a->GetArea() << endl;
      cout << b->GetArea() << endl;
    }
    

    An important thing to notice here is - you don't have to know the exact type of the class you're using, just the base type, and you will get the right result. This is very useful in more complex systems as well.

    Have fun learning!

提交回复
热议问题