对多态不同类型存在技术困惑,寻求专业解答
Hey folks! Based on what I've picked up so far, polymorphism in object-oriented programming splits into two core categories: compile-time and runtime polymorphism. Let's break each down clearly, along with related binding concepts, and wrap up with a code example to tie it all together.
Compile-Time Polymorphism
This type of polymorphism is resolved entirely by the compiler before your program runs. The compiler determines exactly which function or operator to execute during the compilation phase, based on the context of the call.
Common examples include:
- Function Overloading: Defining multiple functions with the same name but different parameter lists (varying in type, count, or order of parameters)
- Operator Overloading: Re-defining the behavior of standard operators (like
+,-, or<<) for custom class types
Runtime Polymorphism
Unlike compile-time polymorphism, this is resolved while the program is running. The exact function to call is determined dynamically, based on the actual type of the object being referenced at runtime.
Key examples here are:
- Function Overriding: When a derived class provides its own implementation of a function that's already defined in its base class
- Virtual Functions: Marking a base class function as
virtualenables derived classes to override it, triggering dynamic dispatch (late binding)
Binding: Early vs Late
These concepts directly map to the two polymorphism types:
- Early Binding: Used for compile-time polymorphism. The compiler links the function call to its specific definition during compilation.
- Late Binding: Used for runtime polymorphism. The function call is resolved at runtime, typically using virtual function tables (v-tables) to look up the correct implementation.
Example Code
Here's a C++ snippet that demonstrates both types of polymorphism and binding:
#include <iostream> using namespace std; // Base class class Base { public: // Virtual function enables runtime polymorphism virtual void display() { cout << "Base class display function" << endl; } // Overloaded functions for compile-time polymorphism void print(int num) { cout << "Integer: " << num << endl; } void print(string msg) { cout << "String: " << msg << endl; } }; // Derived class class Derived : public Base { public: // Override base class virtual function void display() override { cout << "Derived class display function" << endl; } }; int main() { // Compile-time polymorphism in action (function overloading) Base baseObj; baseObj.print(100); baseObj.print("Hello Polymorphism!"); // Runtime polymorphism in action (virtual function overriding) Base* basePtr = new Derived(); basePtr->display(); // Calls Derived's display() thanks to late binding delete basePtr; return 0; }
内容的提问来源于stack exchange,提问作者Shiladitya Bose

