函数重载和虚函数同为同一名称空间内定义不同行为函数。重载在编译时绑定,参数类型必须不同;虚函数在运行时绑定,无参数限制。重载实现函数变体,虚函数实现多态性。
C++ 函数重载与虚函数的异同
函数重载
虚函数
异同
共同点:
不同点:
特性 | 函数重载 | 虚函数 |
---|---|---|
绑定时机 | 编译时 | 运行时 |
参数限制 | 参数类型必须不同 | 没有限制 |
多态性 | 静态多态性 | 动态多态性 |
性能 | 比虚函数更快 | 比函数重载慢 |
用途 | 实现函数的不同变体 | 实现多态性 |
实战案例:
函数重载:
int max(int a, int b) { return a > b ? a : b; } double max(double a, double b) { return a > b ? a : b; }
虚函数:
class Shape { public: virtual double area() = 0; // 纯虚函数 }; class Circle : public Shape { public: double radius; double area() override { return 3.14 * radius * radius; } }; class Rectangle : public Shape { public: double length, width; double area() override { return length * width; } }; int main() { Shape* shapes[] = {new Circle(5), new Rectangle(3, 4)}; for (int i = 0; i < 2; i++) { cout << "Area: " << shapes[i]->area() << endl; } return 0; }
在以上示例中: