Polymorphism is an object-oriented programming feature that allows objects to behave differently at runtime, even if they have the same parent class. In C++, polymorphism is achieved through virtual functions and inheritance: Define a base class and a derived class: the base class contains virtual functions, and the derived class inherits the base class and overrides the virtual functions. Use pointers or references: Save the address of the base class object through a pointer or reference, and access objects of different derived classes at runtime. Calling via virtual function: Calling a virtual function in the base class will call the overridden derived class function at runtime. Practical case: In the shape class hierarchy, the Circle and Rectangle classes inherit the Shape class and override the area(), perimeter() and draw() virtual functions, allowing these shapes to be used
Practical application of polymorphism in C++
What is polymorphism?
Polymorphism is a feature in object-oriented programming languages that allows objects to behave differently at runtime, even if they have the same parent class. In C++, polymorphism is achieved through virtual functions and inheritance.
How to use polymorphism?
Practical case: Shape class hierarchy
Base class Shape
class Shape { public: virtual double area() = 0; virtual double perimeter() = 0; virtual void draw() = 0; };
Derived class Circle and Rectangle
class Circle : public Shape { public: ... // 构造函数和数据成员 virtual double area() override; virtual double perimeter() override; virtual void draw() override; }; class Rectangle : public Shape { public: ... // 构造函数和数据成员 virtual double area() override; virtual double perimeter() override; virtual void draw() override; };
Calculate area and perimeter using polymorphism
vector<Shape*> shapes; shapes.push_back(new Circle(...)); shapes.push_back(new Rectangle(...)); for (auto& shape : shapes) { cout << "面积: " << shape->area() << endl; cout << "周长: " << shape->perimeter() << endl; shape->draw(); }
Advantages:
The above is the detailed content of How to use polymorphism to handle differences between different objects in C++?. For more information, please follow other related articles on the PHP Chinese website!