C++多态
1. 多态性概念
多态性指的是同一个接口使用不同的实例而执行不同操作的能力。这允许我们用相同的方式处理不同的数据类型。
2. 多态性的实现方式
2.1 静态多态(编译时多态)
静态多态是在编译时实现的,这通常通过函数重载和运算符重载来完成。
2.1.1 函数重载
函数重载是指在相同的作用域内有多个具有相同名称的函数,但它们的参数类型和/或数量不同。
C++ 代码示例:
#include <iostream>
class Print {
public:
void display(int i) {
std::cout << "Displaying int: " << i << std::endl;
}
void display(double f) {
std::cout << "Displaying double: " << f << std::endl;
}
};
int main() {
Print obj;
obj.display(101); // Displaying int: 101
obj.display(3.14159); // Displaying double: 3.14159
return 0;
}
2.1.2 运算符重载
运算符重载允许已有的运算符在不同的操作数上赋予新的操作。
C++ 代码示例:
#include <iostream>
class Complex {
private:
float real;
float imag;
public:
Complex(): real(0), imag(0) Complex operator + (const Complex& obj) const {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
void display() {
std::cout << "Real: " << real << " Imaginary: " << imag << std::endl;
}
};
int main() {
Complex c1, c2, result;
// ... (code to initialize c1 and c2)
result = c1 + c2;
result.display();
return 0;
}
2.2 动态多态(运行时多态)
动态多态是在程序运行时实现的,主要通过虚函数和继承机制来实现。
2.2.1 虚函数
在基类中声明的虚函数可以在派生类中被重写,调用时会根据对象的实际类型来调用相应的函数。
C++ 代码示例:
#include <iostream>
class Base {
public:
virtual void print() {
std::cout << "Print of Base" << std::endl;
}
};
class Derived : public Base {
public:
void print() override {
std::cout << "Print of Derived" << std::endl;
}
};
void displayPrint(Base& obj) {
obj.print(); // Print will be called based on the object type, not the reference type.
}
int main() {
Base base;
Derived derived;
displayPrint(base); // Calls Base::print()
displayPrint(derived); // Calls Derived::print(), thanks to polymorphism
return 0;
}
3. 多态性的工作原理
3.1 静态多态
编译器在编译期间选择使用函数的哪个版本,这是基于函数的签名(名称、参数类型、参数个数)。
3.2 动态多态
动态多态的工作机制依赖于虚函数表(v-table)。如果类中有虚函数,编译器会为这个类创建一个v-table。每个对象都会有一个指向v-table的指针(通常称为vptr)。v-table是类的函数地址表,如果调用对象的虚函数,它会使用vptr来确定应该调用哪个函数。
4. 总结
多态性使得我们可以编写更通用和可扩展的代码。静态多态是在编译时解析的,而动态多态是在运行时解析的。理解多态性和它在C++中的实现是面向对象编程的一个重要方面。