Home > Article > Backend Development > How to implement polymorphism in C++ class design?
Polymorphism allows derived classes to have different behaviors while sharing the same interface. The steps to achieve this include: creating base classes, derived classes, virtual functions, and using base class pointers. The sample code shows how to use the shape class hierarchy. Structures (Shape, Rectangle, Circle) implement polymorphism and calculate the total area of different shapes.
Class design to implement polymorphism in C++
What is polymorphism?
Polymorphism allows derived classes to have different behaviors from base classes while sharing the same interface. It provides an elegant way to create collections of objects with similar behavior but different implementations.
Steps to achieve polymorphism:
Practical case:
Consider a hierarchy of shape classes:
class Shape { public: virtual double area() = 0; // 纯虚函数(必须在派生类中重新定义) }; class Rectangle : public Shape { public: Rectangle(double width, double height) : width_(width), height_(height) {} double area() override { return width_ * height_; } private: double width_; double height_; }; class Circle : public Shape { public: Circle(double radius) : radius_(radius) {} double area() override { return 3.14 * radius_ * radius_; } private: double radius_; };
Usage:
// 创建不同形状的集合 vector<Shape*> shapes; shapes.push_back(new Rectangle(2.0, 3.0)); shapes.push_back(new Circle(4.0)); // 使用基类指针计算总面积 double totalArea = 0.0; for (Shape* shape : shapes) { totalArea += shape->area(); // 使用多态性动态绑定函数调用 } // 输出总面积 cout << "Total area: " << totalArea << endl;
Output:
Total area: 37.68
The above is the detailed content of How to implement polymorphism in C++ class design?. For more information, please follow other related articles on the PHP Chinese website!