
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;
}函数重写
立即学习“C++免费学习笔记(深入)”;
函数重写允许派生类中定义的函数与基类中具有相同名称和参数类型的函数具有不同的实现。例如,我们有一个基类 Shape,其中定义了一个计算面积的函数:
本文和大家重点讨论一下Perl性能优化技巧,利用Perl开发一些服务应用时,有时会遇到Perl性能或资源占用的问题,可以巧用require装载模块,使用系统函数及XS化模块,自写低开销模块等来优化Perl性能。 Perl是强大的语言,是强大的工具,也是一道非常有味道的菜:-)利用很多perl的特性,可以实现一些非常有趣而实用的功能。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
class Shape {
public:
virtual double getArea() = 0; // 虚拟函数声明
};子类 Rectangle 和 Circle 覆盖了 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;
}
};实战案例
考虑以下示例,它使用函数重载和函数重写来创建一个计算形状面积的程序:
#includeusing 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 函数,由子类 Rectangle 和 Circle 覆盖。printArea 函数使用函数重载来处理不同类型的 Shape 对象并打印它们的面积。










