MST

星途 面试题库

面试题:C++中多态的两种类型及实现方式简述

请阐述C++中静态多态和动态多态分别是什么,以及它们各自是如何实现的,并分别举例说明。
14.3万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

静态多态

  1. 定义:静态多态是指在编译期确定函数调用的绑定关系,即在编译阶段就知道要调用哪个函数。它基于函数重载和模板机制实现。
  2. 实现方式
    • 函数重载:在同一个作用域内,可以有多个同名函数,但函数的参数列表(参数个数、类型或顺序)不同。编译器根据调用函数时提供的实际参数来决定调用哪个函数。
    • 模板:函数模板和类模板允许编写通用代码,编译器会根据使用模板时提供的实际类型生成具体的函数或类。
  3. 举例
// 函数重载示例
#include <iostream>

void print(int num) {
    std::cout << "Printing integer: " << num << std::endl;
}

void print(double num) {
    std::cout << "Printing double: " << num << std::endl;
}

int main() {
    print(5); 
    print(3.14); 
    return 0;
}
// 函数模板示例
#include <iostream>

template <typename T>
void print(T num) {
    std::cout << "Printing value: " << num << std::endl;
}

int main() {
    print(5); 
    print(3.14); 
    print('a'); 
    return 0;
}

动态多态

  1. 定义:动态多态是指在运行期确定函数调用的绑定关系,即直到程序运行时才知道要调用哪个函数。它基于虚函数和指针或引用实现。
  2. 实现方式
    • 虚函数:在基类中使用 virtual 关键字声明的成员函数。派生类可以重写(override)这些虚函数。
    • 指针或引用:通过基类指针或引用调用虚函数时,根据指针或引用实际指向的对象类型,在运行时决定调用哪个类的虚函数版本。
  3. 举例
#include <iostream>

class Shape {
public:
    virtual void draw() {
        std::cout << "Drawing a shape" << std::endl;
    }
};

class Circle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a circle" << std::endl;
    }
};

class Rectangle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a rectangle" << std::endl;
    }
};

int main() {
    Shape* shape1 = new Circle();
    Shape* shape2 = new Rectangle();

    shape1->draw(); 
    shape2->draw(); 

    delete shape1;
    delete shape2;
    return 0;
}