Home  >  Article  >  Backend Development  >  Practical application cases of C++ function overloading and rewriting

Practical application cases of C++ function overloading and rewriting

PHPz
PHPzOriginal
2024-04-20 08:42:02503browse

C++ 函数重载和重写的实际应用案例

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;
}
subclasses

Rectangle

and Circle override

getArea

function and provides its own implementation: <pre class='brush:cpp;toolbar:false;'>class Shape { public: virtual double getArea() = 0; // 虚拟函数声明 };</pre>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

getArea

function, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn