Function overloading allows functions with the same name to be defined in the same scope, but requires different parameter lists; function rewriting allows functions with the same name and parameter list as those of the base class to be defined in derived classes, requiring the override keyword to be returned The type and parameter list are identical to the base class function. Overloading examples: print(int), print(double); overwriting examples: foo() in the Derived class overrides foo() in the Base class.
C language standard specifications for function overloading and rewriting
Function overloading
Overloading allows multiple functions to be defined in the same scope with the same name, but their parameter lists must be different. The C language standard requires function overloading to follow the following specifications:
Example:
void print(int x); void print(double x);
Function overriding
Overriding allows defining a function in a derived class that is the same as the base A function with the same name and parameter list in the class. The C language standard requires function rewriting to follow the following specifications:
Example:
class Base { public: virtual void foo(); }; class Derived : public Base { public: override void foo() override; // 重写基类中的 foo };
Practical case
Function overloading:
#include <iostream> using namespace std; void print(int x) { cout << "int: " << x << endl; } void print(double x) { cout << "double: " << x << endl; } int main() { print(10); // 调用 int 版本的 print print(3.14); // 调用 double 版本的 print return 0; }
Function rewriting:
#include <iostream> using namespace std; class Shape { public: virtual void draw() = 0; // 纯虚函数 }; class Rectangle : public Shape { public: void draw() override { cout << "Drawing a rectangle" << endl; } }; int main() { Rectangle r; r.draw(); // 调用 Rectangle 类中的重写函数 return 0; }
The above is the detailed content of C++ language standard specifications for function overloading and rewriting. For more information, please follow other related articles on the PHP Chinese website!