Home > Article > Backend Development > What is the difference between C++ function overloading and rewriting?
C Function overloading and rewriting: Overloading: The function with the same name has different parameter types or numbers, and the appropriate version is selected during compilation. Rewriting: A function in a derived class with the same name as the base class overrides the base class implementation and provides a specific implementation for the derived class. Overloading characteristics: different parameter types or numbers, bound at compile time. Overriding characteristics: Same parameter type and number, runtime binding, inheritance required.
C function overloading and rewriting: concepts and differences
Overloading
int sum(int a, int b); double sum(double a, double b);
Override
class Base { public: virtual int add(int a, int b); }; class Derived : public Base { public: int add(int a, int b) override; };
Difference
Features | Overload | Override |
---|---|---|
Access Level | Public or Private | Public or Protected |
Inherited | Not required | Required |
Parameters | Parameters Different types or numbers | Same parameter type and number |
Binding | Compile time | Run time |
Scope | Within the same class | In base class and derived class |
Practical case
Overload: Calculate the sum of numbers of different types
#include <iostream> using namespace std; int sum(int a, int b) { return a + b; } double sum(double a, double b) { return a + b; } int main() { cout << "整数之和:" << sum(1, 2) << endl; cout << "浮点数之和:" << sum(1.5, 2.5) << endl; return 0; }
Override: Calculate the area of various shapes using polymorphism
#include <iostream> using namespace std; class Shape { public: virtual double area() = 0; // 纯虚函数 }; class Rectangle : public Shape { public: Rectangle(double length, double width) : length(length), width(width) {} double area() override { return length * width; } private: double length; double width; }; class Circle : public Shape { public: Circle(double radius) : radius(radius) {} double area() override { return 3.14 * radius * radius; } private: double radius; }; int main() { Shape* shapes[] = {new Rectangle(5, 10), new Circle(4)}; for (int i = 0; i < 2; i++) { cout << "面积:" << shapes[i]->area() << endl; } return 0; }
The above is the detailed content of What is the difference between C++ function overloading and rewriting?. For more information, please follow other related articles on the PHP Chinese website!