C++ 的重载
具有两个相同名称但参数不同的函数的过程称为函数重载。
通过使用不同类型的参数或不同数量的参数来重新定义该函数。只有通过这些差异,编译器才能区分函数。
函数重载的优点是它可以提高程序的可读性,因为您无需为同一操作使用不同的名称。
简单的示例:
#include <iostream> using namespace std; class Base { public: int sum(int a, int b) { return a + b; } int sum(int a, int b, int c) { return a + b + c; } }; int main() { Base obj; cout << obj.sum(1, 2) << endl; cout << obj.sum(1, 2, 3) << endl; return 0; }
运算符重载示例:
#include <iostream> using namespace std; class Shape { private: int length; int width; public: Shape(int l, int w) { length = l; width = w; } double Area() { return length * width; } int operator*(Shape shapeIn) { return Area() * shapeIn.Area(); } }; int main() { Shape sh1(4, 4); Shape sh2(2, 6); int total = sh1 * sh2; cout << "\nsh1.Area() = " << sh1.Area(); cout << "\nsh2.Area() = " << sh2.Area(); cout << "\nTotal = " << total; return 0; }
另附:https://www.educative.io/edpresso/what-is-overloading-in-cpp

浙公网安备 33010602011771号