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
Shape which 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;
}
and Circle
override
function and provides its own implementation: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:cpp;toolbar:false;'>class Shape {
public:
virtual double getArea() = 0; // 虚拟函数声明
};</pre><div class="contentsignin">Copy after login</div></div>
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, the Shape class defines a virtual
getAreafunction, subclassed by
Rectangle and Circle
overrides. The printArea
function uses function overloading to handle different types of Shape
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!