Home > Backend Development > C++ > body text

Practical application cases of C++ function overloading and rewriting

PHPz
Release: 2024-04-20 08:42:02
Original
549 people have browsed it

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;
}
Copy after login
subclasses

Rectangle

and Circle override

getArea

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;
  }
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template