C++中的多态(Polymorphism)是一种面向对象编程(Object-Oriented Programming)的特性,它允许不同的对象对同一消息做出不同的响应。多态性是面向对象编程的三大特性之一,另外两个是封装(Encapsulation)和继承(Inheritance)。
多态性是通过虚函数(Virtual Function)来实现的。虚函数是在基类中声明的函数,它可以被派生类重写(Override)。当基类指针或引用指向派生类对象时,调用虚函数时将会根据实际对象类型来确定调用哪个函数。这种行为被称为动态绑定(Dynamic Binding)或运行时多态性(Run-time Polymorphism)。
C++中的多态性可以分为两种:静态多态性(Static Polymorphism)和动态多态性(Dynamic Polymorphism)。
静态多态性是指在编译时就能确定函数调用的具体实现。C++中实现静态多态性的方式是函数重载(Function Overloading)和运算符重载(Operator Overloading)。
函数重载是指在同一个作用域内定义多个同名函数,但它们的参数列表不同。编译器在编译时会根据函数调用时传递的参数类型和数量来确定具体调用哪个函数。
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
cout << add(1, 2) << endl; // 调用int add(int a, int b)
cout << add(1.0, 2.0) << endl; // 调用double add(double a, double b)
return 0;
}
运算符重载是指在类中定义与运算符相关的函数,使得该运算符可以用于类的对象。运算符重载可以使得代码更加简洁易读。
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
private:
double real;
double imag;
};
int main() {
Complex c1(1.0, 2.0);
Complex c2(3.0, 4.0);
Complex c3 = c1 + c2;
cout << c3 << endl; // 输出 4+6i
return 0;
}
动态多态性是指在运行时才能确定函数调用的具体实现。C++中实现动态多态性的方式是虚函数。
虚函数是在基类中声明的函数,它可以被派生类重写(Override)。当基类指针或引用指向派生类对象时,调用虚函数时将会根据实际对象类型来确定调用哪个函数。这种行为被称为动态绑定(Dynamic Binding)或运行时多态性(Run-time Polymorphism)。
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
};
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
virtual double area() const {
return width * height;
}
private:
double width;
double height;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
virtual double area() const {
return