21xrx.com
2024-06-03 00:49:26 Monday
登录
文章检索 我的文章 写文章
C++代码的复用技巧
2023-07-08 14:57:04 深夜i     --     --
C++ 复用 代码 技巧 函数模板

在C++编程过程中,代码复用是提高开发效率和减少编程错误的关键技巧之一。代码复用可以让我们在不同项目中重复使用同样的代码,也可以在一个项目中多次使用相同的代码,从而大大提高编程效率。下面将介绍一些常用的C++代码复用技巧。

1. 函数模板

函数模板是一种可以根据不同的数据类型来生成具体代码的技术。其格式如下:


template <typename T>

T max(T a, T b) {

  return a > b ? a : b;

}

模板中的 `typename T` 定义了一个模板类型参数。在调用函数时,可以将任何数据类型传递给该函数,例如 `max(1, 2)`、`max("hello", "world")` 等。

2. 类模板

类模板是一种可以根据不同的数据类型来生成具体代码的技术。其格式如下:


template <typename T>

class Stack {

private:

  T data[100];

  int top;

public:

  void push(T x) {

    data[top++] = x;

  }

  T pop() {

    return data[--top];

  }

};

在调用该类时,可以将任何数据类型传递给该类,例如 `Stack s1`、`Stack s2` 等。

3. 继承

继承是一种代码复用技巧,可以让一个类继承另一个类的属性和方法。被继承的类称为父类或基类,继承的类称为子类或派生类。例如:


class Person {

protected:

  string name;

public:

  Person(string name)

    this->name = name;

  

  void sayHello() my name is " << name << endl;

  

};

class Student : public Person {

public:

  Student(string name) : Person(name) {}

  void study()

    cout << name << " is studying." << endl;

  

};

int main() {

  Student s("Tom");

  s.sayHello(); // 输出 "Hello, my name is Tom"

  s.study(); // 输出 "Tom is studying."

  return 0;

}

4. 多态

多态是一种代码复用技巧,可以让一个对象在不同的情况下呈现不同的行为。多态可以通过虚函数和纯虚函数来实现。例如:


class Shape {

public:

  virtual double area() = 0;

};

class Rectangle : public Shape {

private:

  double width, height;

public:

  Rectangle(double width, double height)

    this->width = width;

    this->height = height;

  

  virtual double area() {

    return width * height;

  }

};

class Circle : public Shape {

private:

  double radius;

public:

  Circle(double radius)

    this->radius = radius;

  

  virtual double area() {

    return 3.1415926 * radius * radius;

  }

};

int main() {

  Shape *s1 = new Rectangle(3, 4);

  Shape *s2 = new Circle(5);

  cout << s1->area() << endl; // 输出 12

  cout << s2->area() << endl; // 输出 78.5398

  delete s1;

  delete s2;

  return 0;

}

通过以上几种技巧,我们可以大大提高C++编程效率和程序性能,实现代码的高效复用。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复