In C, function overloading allows the creation of functions with the same name but different parameter lists. Function overriding occurs in a derived class. The function defined in the derived class and the function of the same name in the base class override the method of the base class.
Function overloading and function overriding in C
Introduction
Function Overloading and function overriding are two important features in C that allow functions with the same name to be created in different ways. This tutorial explains both concepts and provides practical examples.
Function Overloading
Function overloading allows the creation of multiple functions with the same name but different parameter lists. When the compiler calls a function, it determines the correct function to call based on the argument list.
Grammar
type function_name(parameter_list1); type function_name(parameter_list2);
Practical case
The following code demonstrates function overloading:
#include <iostream> int sum(int a, int b) { return a + b; } double sum(double a, double b) { return a + b; } int main() { std::cout << sum(1, 2) << std::endl; // 输出:3 std::cout << sum(1.5, 2.5) << std::endl; // 输出:4 }
Function coverage
Function coverage occurs in a derived class. The function defined in the derived class has the same name and parameter list as the function defined in the base class. The methods of the derived class will override the methods of the base class.
Grammar
class DerivedClass : public BaseClass { public: type function_name(parameter_list); // 覆盖 BaseClass 中的方法 };
Practical case
The following code demonstrates function coverage:
#include <iostream> class Shape { public: virtual double area() const = 0; }; class Square : public Shape { public: Square(double side_length) : side_length(side_length) {} double area() const override { return side_length * side_length; } private: double side_length; }; int main() { Square square(5); std::cout << square.area() << std::endl; // 输出:25 }
Conclusion
Function overloading and function overriding are two powerful features in C that allow the creation of functions with the same name with different behaviors. Function overloading is used to create a function with a different parameter list, while function overriding is used to override a base class method in a derived class.
The above is the detailed content of Function overloading and function overriding in C++. For more information, please follow other related articles on the PHP Chinese website!