C ++ Polymorphism
Not long ago, I met Kingsoft, which was quite smooth. On the other hand, the interviewer asked the c ++ question, which seemed to be a poor answer. Later, he asked the question about polymorphism. Let me describe it, or write an example, I had 2 at that time, so I would like to review it here.
Multi-state ". In oop, multiple implementation methods of interfaces are polymorphism. Polymorphism is a technique that allows you to set a parent object to be equal to one or more other sub-objects, the parent object can operate in different ways according to the features of the sub-objects currently assigned to it. To put it simply, assign a child pointer to a parent pointer.
In c ++, the following methods are used to implement polymorphism: virtual functions, abstract classes, rewriting, overwriting, and templates.
First, implement a virtual function.
#include <iostream>using namespace std;class A{public:A(){}~A(){}virtual void fun(){cout<<"this is A"<<endl;}};class B:public A{public:B(){}~B(){}void fun(){cout<<"this is B"<<endl;}};int main(){A *a = new A();A *b = new B();a->fun();b->fun();if (a != NULL)delete a;if (b != NULL)delete b;return 0;}
The running result is as follows:
How to Implement polymorphism with standard C
Struct Base
{
Int (* foo_ptr) (Base *);
};
Struct Derived_A
{
Struct Base;
Int x;
};
Int Derived_A_foo (Base * p)
{
Return (Derived_A *) p)-> x;
}
Void Derived_A_Construct (Derived_A * p)
{
P-> foo_ptr = Derived_A_foo;
P-> x = 0;
}
Struct Derived_A;
Struct Base * x = (Base *);
Derived_A_Construct (& );
X-> foo_ptr (x );
This is not a strict approach, but a rough description.
Types of c ++ polymorphism and their respective implementation mechanisms
Polymorphism, that is, "one interface, multiple implementations ".
Polymorphism in C ++ can be divided into static polymorphism, including: function overload, template, and dynamic polymorphism, including: virtual function.
Static: all information about the called function must be known during compilation, but dynamic: The specific called function is not determined until the runtime. For details, check the three keywords "function overload", "template", and "virtual function" respectively.