To solve the problem that the object type cannot be correctly identified, c ++ providesPolymorphism
(Polymorphism)
To solve the problem. For example program 1, this method can determine which overloaded member function is called during compilation.
CalledFirst
Joint Compilation
(Early binding), while the system can determine which overloaded member function to call based on its type at runtime.
, CalledPolymorphism
, OrLagging Compilation
(Late
Binding). The following figure shows the Example 3: delayed Association. Delayed Association is the solution to the problem of polymorphism.
The Code is as follows:
// Example 3
# Include <iostream
>
Using
Namespace
Std;
Class
Vehicle
{
Public
:
Vehicle (float
Speed, int
Total)
{
Vehicle: speed =
Speed;
Vehicle: total =
Total;
}
Virtual
Void
ShowMember () // virtual function
{
Cout
<Speed <"|" <total <endl;
}
Protected
:
Float
Speed;
Int
Total;
};
Class
Car: public
Vehicle
{
Public
:
Car (int
Aird, float
Speed, int
Total): Vehicle (speed, total)
{
Car: aird =
Aird;
}
Virtual
Void
ShowMember () // virtual function, in the derived class, because
The inherited link. The virtual field can also be left empty.
{
Cout
<Speed <"|" <total <"|" <aird <endl;
}
Public
:
Int
Aird;
};
Void
Test (Vehicle & temp)
{
Temp. ShowMember ();
}
Int
Main
()
{
Vehicle a (120,4 );
Car B (180,110, 4 );
Test ();
Test (B );
Cin
. Get ();
}
Definition of virtual functions on which polymorphism features work
AddVirtual
Off
The member function becomes a virtual function. From the result of running the code in the preceding example, the system successfully identifies the real type of the object, the respective overload member functions are successfully called.
The polymorphism feature saves programmers the consideration of details, improves development efficiency, and greatly simplifies code. Of course, the definition of virtual functions is also flawed, some data storage and execution commands are added due to polymorphism.
Sales, so it is best not to use polymorphism.