Function rewriting and template programming are powerful techniques in C for enabling code extension and generalization. Function overriding enables extension by overriding base class methods in derived classes; template programming enables generalization by creating generic code that can be used in various types. A practical example demonstrates the use of function rewriting and template programming to calculate the area of a shape, showing the use of both techniques in extending and generalizing code.
Function rewriting and template programming are powerful techniques in C programming , allowing developers to create scalable and versatile code.
Function overriding
Function overriding enables code extension by allowing alternative implementations of base class methods to be provided in derived classes. The syntax is as follows:
class Derived : public Base { public: // 重写基类方法 override double calculate() { // 自定义实现 ... } };
Template Programming
Template programming allows the creation of generic code that can be used for various types. The syntax is as follows:
template<typename T> class MyClass { T data; ... };
Practical case
Consider a program for calculating the areas of different shapes:
// 使用基类和函数重写 class Shape { public: virtual double calculateArea() = 0; }; class Square : public Shape { // 使用函数重写扩展基类 public: double side; Square(double side) : side(side) {} double calculateArea() override { return side * side; } }; class Circle : public Shape { // 再次使用函数重写扩展基类 public: double radius; Circle(double radius) : radius(radius) {} double calculateArea() override { return 3.14 * radius * radius; } }; int main() { Square s(5); Circle c(10); cout << "Square area: " << s.calculateArea() << endl; cout << "Circle area: " << c.calculateArea() << endl; }
// 使用模板编程 template<typename T> class Shape { T side; public: Shape(T side) : side(side) {} T calculateArea() { return side * side; } // 通用实现 }; // 使用模板实例化创建特定形状 class Square : public Shape<double> {}; class Circle : public Shape<double> {}; int main() { Square s(5); Circle c(10); cout << "Square area: " << s.calculateArea() << endl; cout << "Circle area: " << c.calculateArea() << endl; }
The above is the detailed content of Function Rewriting and Template Programming: Revealing the Magical Uses of Code Expansion and Code Generalization. For more information, please follow other related articles on the PHP Chinese website!