How can polymorphism be implemented in the C language?
In C language, polymorphism can be implemented using function pointers and structures. The specific steps are as follows:
- Define a base class structure that includes a function pointer member to point to member functions of different derived classes.
typedef struct {
void (*func)();
} Base;
- Define a derived class structure and define specific member functions within it.
typedef struct {
Base base;
// 派生类的其他成员
} Derived;
- Implement member functions of the derived class.
void derived_func() {
// 派生类的具体实现
}
- Assign the member functions of the derived class to the function pointers of the base class.
Derived derived;
Base* base = (Base*)&derived;
base->func = derived_func;
- Invoke polymorphic function.
base->func();
This achieves polymorphism in the C language. During runtime, different derived class implementations are called based on the specific member function pointed to by the function pointer.