Function overloading allows functions with the same name but different signatures in a class, while function overriding occurs in a derived class when it overrides a function with the same signature in the base class, providing different behavior.
The difference between function overloading and rewriting in C
Function overloading
Function overloading allows the use of different functions with the same name in the same class, as long as their signatures (parameter types and number) are different.
Syntax:
return_type function_name(parameter_types) { // 函数体 } // 另一个重载 return_type function_name(other_parameter_types) { // 另一个函数体 }
Practical case:
Consider a class named AreaCalculator
, It calculates the area of different shapes:
class AreaCalculator { public: double Area(double radius) { return M_PI * radius * radius; } double Area(double length, double width) { return length * width; } double Area(int numOfSides, double sideLength) { // 正多边形的面积公式 // ... 省略后面代码 } };
Here, the Area
function is overloaded to receive a different number and type of arguments, allowing different areas to be calculated based on the shape type.
Function overriding
Function overriding occurs in a derived class when it overrides a function in the base class with the same signature (name and parameter types). Overridden functions in derived classes often behave differently than functions in base classes.
Syntax:
class DerivedClass : public BaseClass { public: // 重写基类中的函数 return_type function_name(parameter_types) { // 重写的函数体 } };
Practical case:
Consider a base class named Shape
, which defines a Draw
function to draw shapes:
class Shape { public: virtual void Draw() { // 绘制通用形状 // ... 省略后面代码 } };
Derived classes Circle
can override the Draw
function to specifically draw circles:
class Circle : public Shape { public: void Draw() override { // 绘制圆形 // ... 省略后面代码 } };
By overriding, the Draw
function of the Circle
class will override the Draw
function of the Shape
class, and Provides a more specific drawing implementation.
The above is the detailed content of How to distinguish function overloading and rewriting in C++. For more information, please follow other related articles on the PHP Chinese website!