c++++ 多态性允许对象以多种方式使用,通过虚函数和虚表实现。它使派生类对象的行为与基类不同:虚函数允许在派生类中覆盖基类函数。虚表保存指向虚函数地址的指针,根据对象类型动态查找和调用适当的函数。实战示例展示了如何使用多态性创建动态对象集合,根据其类型调整行为,增强代码灵活性。

C++ 中的多态性:实现灵活性与可扩展性的利器
概述
多态性是面向对象编程 (OOP) 中的一项基本原则,允许对象以多种不同的方式被使用。它通过允许派生类对象的行为与它们的基类不同来实现这一点。
立即学习“C++免费学习笔记(深入)”;
实现多态性
在 C++ 中,可以通过使用虚函数和虚表来实现多态性。虚函数是允许在派生类中覆盖基类函数的函数。虚表是一个保存指向虚函数地址的指针的表。
虚函数
class Base {
public:
virtual void display() {
cout << "Base class display function" << endl;
}
};
class Derived : public Base {
public:
virtual void display() override {
cout << "Derived class display function" << endl;
}
};在上面的示例中,Base 类的 display 函数是虚函数,在派生类 Derived 中被覆盖。
虚表
虚表包含指向 Base 类和 Derived 类的 display 函数地址的指针:
class Base {
public:
virtual void display() {
cout << "Base class display function" << endl;
}
};
class Derived : public Base {
public:
virtual void display() override {
cout << "Derived class display function" << endl;
}
};
int main() {
Base* ptr = new Derived(); // 指向 Derived 对象的 Base 类指针
ptr->display(); // 调用 Derived 类中的 display 函数
}在上述示例中,尽管我们使用的是 Base 类指针,但该指针实际指向派生类 Derived 的一个对象。当调用 display 函数时,它会根据指向的实际对象类型动态查找并调用适当的函数。
实战案例:形状类层次结构
考虑一个形状类层次结构,其中有 Shape 基类和 Circle 和 Rectangle 派生类。Shape 类具有计算面积的虚函数。
class Shape {
public:
virtual float area() = 0; // 纯虚函数
};
class Circle : public Shape {
public:
Circle(float radius) : mRadius(radius) {}
float area() override {
return 3.14 * mRadius * mRadius;
}
private:
float mRadius;
};
class Rectangle : public Shape {
public:
Rectangle(float width, float height) : mWidth(width), mHeight(height) {}
float area() override {
return mWidth * mHeight;
}
private:
float mWidth;
float mHeight;
};在主函数中,我们可以使用 Shape 类指针来存储不同形状对象的引用,并调用 area 函数以计算它们的面积:
int main() {
Shape* shapes[] = {new Circle(5), new Rectangle(10, 5)};
for (Shape* shape : shapes) {
cout << "Area: " << shape->area() << endl;
}
return 0;
}结论
C++ 中的多态性提供了极大的灵活性和可扩展性。它允许创建动态对象集合,这些对象的行为可以根据其实际类型进行调整。这使程序员能够创建维护性更高、更易于扩展的代码。
以上就是C++ 中多态性如何帮助创建灵活且可扩展的代码?的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号