Talk about polymorphism again

The concept of polymorphism

  1. Polymorphic
    concept of polymorphism: Popular, is a variety of forms, specific point is to complete an action, when different objects to completion will produce different states.

2. For
example, the behavior of buying tickets. When ordinary people buy tickets, they buy tickets at full price; when students buy tickets, they buy tickets at half price; when soldiers buy tickets, they buy tickets first.
Let me give you another chestnut: In order to compete for the online payment market recently, Alipay often conducts attractive sweeping red envelope-payment-giving reward activities at the end of the year. Then think about why the red envelopes that someone sweeps are big and fresh at 8 yuan, 10 yuan..., while the red envelopes that someone sweeps are all 1 cent, 5 cents.... In fact, behind this is also a polymorphic behavior. Alipay will first analyze your account data. For example, if you are a new user, if you don’t pay with Alipay frequently, etc., then you need to be encouraged to use Alipay, then the amount of your scan code = random()%99; for example, you often use Alipay If you don’t have any money in your payment or Alipay account all the year round, then you don’t need to encourage you to use Alipay too much. Then the amount of your scan code = random()%1; to sum up: the same scan code action, different users scan different This is also a kind of polymorphic behavior. ps: The Alipay red envelope problem is purely fabricated, and it is for entertainment only.
Definition and realization of polymorphism

1. The constituent conditions of polymorphism definition

Polymorphism is when the same function is called on class objects with different inheritance relationships, resulting in different behaviors. For example, Student inherits Person. Person objects buy tickets at full price, and Student objects buy tickets at half price.

Then there are two more conditions to form polymorphism in inheritance:

调用函数的对象必须是指针或者引用
被调用的函数必须是虚函数,且完成了虚函数的重写

What is the virtual function mentioned here?

虚函数:就是在类的成员函数的前面加virtual关键字

What is the rewriting of virtual functions?

虚函数的重写:派生类中有一个跟基类的完全相同虚函数,我们就称子类的虚函数重写了基类的虚函数,完全相同是指:函数名、参数、返回值都相同。另外虚函数的重写也叫作虚函数的覆盖

Guess you like

Origin blog.51cto.com/2096101/2593395