多态性的真正意义(用途)是什么 [英] What is the real significance(use) of polymorphism
问题描述
我是OOP的新手.尽管我了解多态是什么,但我无法真正使用它.我可以使用其他名称的函数.为什么我应该尝试在我的应用程序中实现多态性.
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 polymorphism in my application.
推荐答案
经典答案:想象一个基类Shape
.它公开了一个GetArea
方法.想象一个Square
类,一个Rectangle
类以及一个Circle
类.无需创建单独的GetSquareArea
,GetRectangleArea
和GetCircleArea
方法,您只需在每个派生类中实现一个方法即可.您不必知道使用哪个确切的Shape
子类,只需调用GetArea
即可获得结果,而与它的具体类型无关.
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.
看看这段代码:
#include <iostream>
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.
学习愉快!
这篇关于多态性的真正意义(用途)是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!