21xrx.com
2024-09-19 08:55:42 Thursday
登录
文章检索 我的文章 写文章
C++代码复用的方法
2023-07-12 10:47:53 深夜i     --     --
继承 (Inheritance) 组合 (Composition) 模板 (Templates) 命名空间 (Namespace) 宏定义 (Mac

C++是一种高级编程语言,被广泛用于开发计算机软件。在开发过程中,重用代码可以大大减少开发时间,提高代码可维护性和可靠性。在这篇文章中,我们将讨论一些C++代码复用的方法。

1.函数模板:函数模板是一种使用通用类型来定义函数的方法,可以使同一函数处理多种不同类型的数据。例如,下面的代码定义了一个函数模板,可以用于计算两个不同类型的数的和:


template <typename T, typename U>

T add(T t, U u)

{

  return t + u;

}

使用时,可以使用该模板函数来计算整数或浮点数之和:


int a = 10;

float b = 20.5;

cout << add(a, b); //输出结果为30.5

2.类模板:类模板是一种使用通用类型来定义类的方法,可以用于创建一个通用的类来处理多种不同类型的数据。例如,下面的代码定义了一个类模板,可以用于创建一个通用的栈类:


template <typename T>

class Stack

{

private:

  T array[100];

  int top;

public:

  Stack();

  void push(T t);

  T pop();

};

template <typename T>

Stack<T>::Stack()

  top = -1;

template <typename T>

void Stack<T>::push(T t)

{

  array[++top] = t;

}

template <typename T>

T Stack<T>::pop()

{

  return array[top--];

}

使用时,可以使用该模板类来创建一个整数或浮点数栈:


Stack<int> intStack;

Stack<float> floatStack;

3.继承:在C++中,可以使用继承来复用现有类的属性和方法。子类可以继承父类的属性和方法,并且可以添加自己的属性和方法。例如,下面的代码定义了一个父类Shape,和两个子类Circle和Rectangle:


class Shape

{

protected:

  int width;

  int height;

public:

  Shape(int w, int h);

  virtual int area() = 0;

};

Shape::Shape(int w, int h)

{

  width = w;

  height = h;

}

class Circle : public Shape

{

public:

  Circle(int r);

  int area();

private:

  int radius;

};

Circle::Circle(int r) : Shape(0, 0)

{

  radius = r;

}

int Circle::area()

{

  return 3.14 * radius * radius;

}

class Rectangle : public Shape

{

public:

  Rectangle(int w, int h);

  int area();

};

Rectangle::Rectangle(int w, int h) : Shape(w, h)

{

}

int Rectangle::area()

{

  return width * height;

}

使用时,可以创建一个Circle对象和一个Rectangle对象,并分别调用它们的area()方法:


Circle c(10);

Rectangle r(5, 10);

cout << c.area() << endl; //输出结果为314

cout << r.area() << endl; //输出结果为50

在C++中,代码复用有多种方法。函数模板、类模板和继承都是常用的代码复用方法,可以大大提高开发效率。

  
  

评论区

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