C++——多态(核心中的核心)

44 阅读1分钟

多态 (Polymorphism)

1. 静态多态 (Static Polymorphism)

  • 改进前:  函数重载时,仅返回值类型不同, 编译器无法区分调用哪个函数

    #include <iostream>
    using namespace std;
    
    int add(int a, int b) {
        return a + b;
    }
    
    double add(int a, int b) { // 错误: 与之前的函数声明冲突
        return a + b;
    }
    
    int main() {
        int result1 = add(1, 2); 
        double result2 = add(1.5, 2.5); 
    
        cout << "result1 = " << result1 << endl;
        cout << "result2 = " << result2 << endl;
        return 0;
    }
    
  • 改进后:  修改函数名或参数列表,避免函数重载冲突

    #include <iostream>
    using namespace std;
    
    int addInt(int a, int b) {
        return a + b;
    }
    
    double addDouble(double a, double b) { 
        return a + b;
    }
    
    int main() {
        int result1 = addInt(1, 2); 
        double result2 = addDouble(1.5, 2.5); 
    
        cout << "result1 = " << result1 << endl;
        cout << "result2 = " << result2 << endl;
        return 0;
    }
    

2. 动态多态 (Dynamic Polymorphism)——(虚函数)

  • 改进前:  如果没有将基类函数声明为虚函数,则动态绑定不会发生,调用的是基类的函数

    #include <iostream>
    
    using namespace std;
    
    class Shape {
    public:
        void draw() const { cout << "Drawing a shape." << endl; } // 非虚函数
    };
    
    class Circle : public Shape {
    public:
        void draw() const { cout << "Drawing a circle." << endl; } 
    };
    
    class Square : public Shape {
    public:
        void draw() const { cout << "Drawing a square." << endl; } 
    };
    
    int main() {
        Shape* shape1 = new Circle();
        Shape* shape2 = new Square();
    
        shape1->draw(); // 调用 Shape::draw() 
        shape2->draw(); // 调用 Shape::draw() 
    
        delete shape1;
        delete shape2;
        return 0;
    }
    
  • 改进后:  将基类函数声明为虚函数,实现动态绑定

    #include <iostream>
    
    using namespace std;
    
    class Shape {
    public:
        virtual void draw() const { cout << "Drawing a shape." << endl; } // 虚函数
    };
    
    class Circle : public Shape {
    public:
        void draw() const override { cout << "Drawing a circle." << endl; } 
    };
    
    class Square : public Shape {public:
        void draw() const override { cout << "Drawing a square." << endl; } 
    };
    
    int main() {
        Shape* shape1 = new Circle();
        Shape* shape2 = new Square();
    
        shape1->draw(); // 调用 Circle::draw() 
        shape2->draw(); // 调用 Square::draw() 
    
        delete shape1;
        delete shape2;
        return 0;
    }
    

虚函数的多态行为需要满足以下三个必要条件

  • 基类声明虚函数
  • 派生类重写(override)虚函数
  • 通过指针或引用调用