Home >Backend Development >C++ >Understanding and using C++ function overloading and rewriting
Function overloading in C allows functions with the same name to be defined in the same class, but with different parameter lists; function rewriting occurs when a function with the same name and parameters as the parent class is defined in a subclass, and the subclass function will overwrite the parent class function. . In the practical example, the overloaded function is used to perform addition operations for different data types, and the overridden function is used to override the virtual function in the parent class to calculate the area of different shapes.
C function overloading and rewriting: in-depth understanding and practical application
Function overloading
Function overloading allows multiple functions to be defined in the same class with the same function name but different parameter lists.
class MyClass { public: int add(int a, int b); double add(double a, double b); }; int MyClass::add(int a, int b) { return a + b; } double MyClass::add(double a, double b) { return a + b; }
Function overriding
Function overriding occurs when a function is defined in a child class with the same name and the same parameter list as the parent class. Subclass functions will override parent class functions.
class ParentClass { public: virtual int display() { return 10; } }; class ChildClass : public ParentClass { public: int display() { // 重写父类的 display() return 20; } };
Practical case
Overloaded function example:
#include <iostream> class Calculator { public: int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } std::string add(std::string a, std::string b) { return a + b; } }; int main() { Calculator calc; std::cout << calc.add(1, 2) << std::endl; // 输出:3 std::cout << calc.add(1.5, 2.5) << std::endl; // 输出:4 std::cout << calc.add("Hello", "World") << std::endl; // 输出:HelloWorld return 0; }
Rewritten function example:
#include <iostream> class Shape { public: virtual double area() = 0; // 纯虚函数(强制子类实现 area()) }; class Rectangle : public Shape { public: Rectangle(double width, double height) : m_width(width), m_height(height) {} double area() override { return m_width * m_height; } private: double m_width; double m_height; }; class Circle : public Shape { public: Circle(double radius) : m_radius(radius) {} double area() override { return 3.14 * m_radius * m_radius; } private: double m_radius; }; int main() { Rectangle rect(5, 10); Circle circle(5); std::cout << "Rectangle area: " << rect.area() << std::endl; // 输出:50 std::cout << "Circle area: " << circle.area() << std::endl; // 输出:78.5 return 0; }
The above is the detailed content of Understanding and using C++ function overloading and rewriting. For more information, please follow other related articles on the PHP Chinese website!