Practical application cases of C function overloading and rewriting
Function overloading
Function overloading allows the same function name to have different implementations to handle different types or numbers of arguments. For example, we can create a function that prints different types of data: Functions with the same name and parameter types have different implementations. For example, we have a base class
Shapewhich defines a function to calculate the area:
void print(int value) { cout << value << endl; } void print(double value) { cout << value << endl; } int main() { int num = 10; double number = 12.5; print(num); // 调用 print(int) print(number); // 调用 print(double) return 0; }
andCircle
override
function and provides its own implementation:class Shape { public: virtual double getArea() = 0; // 虚拟函数声明 };
Practical Case
Consider the following example, which uses function overloading and function overriding to Create a program that calculates the area of a shape:
class Rectangle: public Shape { public: double width, height; Rectangle(double width, double height) : width(width), height(height) {} double getArea() override { return width * height; } }; class Circle: public Shape { public: double radius; Circle(double radius) : radius(radius) {} double getArea() override { return 3.14 * radius * radius; } };
In this case, theShapeclass defines a virtual
getAreafunction, subclassed by
RectangleandCircle
overrides. TheprintArea
function uses function overloading to handle different types ofShape
objects and print their areas.
The above is the detailed content of Practical application cases of C++ function overloading and rewriting. For more information, please follow other related articles on the PHP Chinese website!