
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,其中定义了一个计算面积的函数:
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;
}
};实战案例
考虑以下示例,它使用函数重载和函数重写来创建一个计算形状面积的程序:
#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 函数,由子类 Rectangle 和 Circle 覆盖。printArea 函数使用函数重载来处理不同类型的 Shape 对象并打印它们的面积。
以上就是C++ 函数重载和重写的实际应用案例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号