首页 > 文章列表 > C++ 函数重载和重写的实际应用案例

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

函数重载 c++ 函数重写
487 2024-04-23

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

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

函数重载

函数重载允许同一个函数名具有不同的实现,以处理不同类型或数量的参数。例如,我们可以创建一个打印不同类型数据的函数:

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

函数重写

函数重写允许派生类中定义的函数与基类中具有相同名称和参数类型的函数具有不同的实现。例如,我们有一个基类 Shape,其中定义了一个计算面积的函数:

class Shape {
public:
  virtual double getArea() = 0; // 虚拟函数声明
};

子类 RectangleCircle 覆盖了 getArea 函数并提供了自己的实现:

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

实战案例

考虑以下示例,它使用函数重载和函数重写来创建一个计算形状面积的程序:

#include <iostream>

using namespace std;

// 基类 Shape
class Shape {
public:
  virtual double getArea() = 0;
};

// 子类 Rectangle
class Rectangle: public Shape {
public:
  double width, height;
  Rectangle(double width, double height) : width(width), height(height) {}
  double getArea() override {
    return width * height;
  }
};

// 子类 Circle
class Circle: public Shape {
public:
  double radius;
  Circle(double radius) : radius(radius) {}
  double getArea() override {
    return 3.14 * radius * radius;
  }
};

// 函数重载用来打印不同类型数据的面积
void printArea(Shape *shape) {
  cout << "Area of the Shape: " << shape->getArea() << endl;
}

int main() {
  Rectangle rectangle(5, 10);
  Circle circle(2);
  printArea(&rectangle);
  printArea(&circle);
  return 0;
}

在这个案例中,Shape 类定义了一个虚拟的 getArea 函数,由子类 RectangleCircle 覆盖。printArea 函数使用函数重载来处理不同类型的 Shape 对象并打印它们的面积。