C++高级特性:模板、异常处理与运算符重载
                           
天天向上
发布: 2025-02-04 00:51:48

原创
896 人浏览过

模板

模板是C++中支持泛型编程的重要特性,允许编写与类型无关的代码,增加代码的复用性。

  • 函数模板
    函数模板允许我们编写能够处理不同数据类型的函数,而不需要重复定义多个版本。
  template <typename T>
  T add(T a, T b) {
      return a + b;
  }

  int main() {
      std::cout << add(3, 4) << std::endl;  // 整型
      std::cout << add(3.5, 4.5) << std::endl;  // 浮点型
  }
  • 类模板
    类模板用于创建一个可以处理多种类型数据的类。它是类的模板定义,编译时决定数据类型。
  template <typename T>
  class Box {
  private:
      T value;
  public:
      Box(T val) : value(val) {}
      T getValue() { return value; }
  };

  int main() {
      Box<int> intBox(10);
      Box<double> doubleBox(3.14);
      std::cout << intBox.getValue() << std::endl;
      std::cout << doubleBox.getValue() << std::endl;
  }
  • 模板的特化
    模板特化用于为特定类型提供不同的实现。特化版本通常用于处理特定类型的数据。
  template <typename T>
  class Printer {
  public:
      void print(T val) { std::cout << val << std::endl; }
  };

  // 特化版本
  template <>
  class Printer<char> {
  public:
      void print(char val) { std::cout << "Char: " << val << std::endl; }
  };

  int main() {
      Printer<int> intPrinter;
      Printer<char> charPrinter;
      intPrinter.print(10);
      charPrinter.print('A');
  }
  • 模板与STL的结合
    C++标准模板库(STL)广泛使用模板来提供各种数据结构和算法,如vectorlistmap等。
  #include <iostream>
  #include <vector>

  int main() {
      std::vector<int> v = {1, 2, 3, 4, 5};
      for (int i : v) {
          std::cout << i << " ";
      }
      std::cout << std::endl;
  }

异常处理

C++通过异常处理机制提供了一种处理程序运行时错误的方法,避免程序崩溃。

  • try, catch, throw
  • throw用于抛出异常。
  • try块用于包含可能抛出异常的代码。
  • catch块用于捕捉并处理异常。
  try {
      int x = 10;
      if (x == 10) {
          throw "Error: x cannot be 10";
      }
  } catch (const char* msg) {
      std::cout << msg << std::endl;
  }
  • 自定义异常
    C++允许自定义异常类,继承标准的异常类并扩展其功能。
  class MyException : public std::exception {
  public:
      const char* what() const noexcept override {
          return "Custom exception occurred!";
      }
  };

  int main() {
      try {
          throw MyException();
      } catch (const MyException& e) {
          std::cout << e.what() << std::endl;
      }
  }
  • 异常的层级和传播
    异常可以层层传播,直到被catch块捕获为止。异常处理机制确保程序不会因错误崩溃,能够在适当的地方处理异常。

运算符重载

运算符重载允许开发者为自定义类型定义操作符,使其能够像内建类型一样进行操作。

  • 运算符的基本概念
    运算符重载允许通过自定义操作符符号,使得类的对象可以执行诸如加法、比较、索引等操作。 示例:
  class Complex {
  public:
      int real, imag;
      Complex operator+(const Complex& other) {
          Complex temp;
          temp.real = real + other.real;
          temp.imag = imag + other.imag;
          return temp;
      }
  };
  • 常见的运算符重载
  • +、-:用于重载加法和减法运算符。
  • []:用于重载数组下标操作符。
  • ():用于重载函数调用运算符。
  • <<、>>:用于流输入输出重载。 示例:
  class Box {
  public:
      int length;
      Box(int len) : length(len) {}

      // 重载[]运算符
      int operator[](int index) {
          return length;
      }
  };

  class Printer {
  public:
      // 重载<<运算符
      friend std::ostream& operator<<(std::ostream& os, const Box& b) {
          os << "Box length: " << b.length;
          return os;
      }
  };

  int main() {
      Box b(10);
      std::cout << b << std::endl;
  }
  • 运算符重载的规则和限制
  1. 不能重载所有运算符(如::.等)。
  2. 运算符重载不改变运算符的优先级和结合性。
  3. 必须至少有一个操作数是类类型。 示例:
  class Complex {
  public:
      int real, imag;
      Complex operator-(const Complex& other) {
          Complex temp;
          temp.real = real - other.real;
          temp.imag = imag - other.imag;
          return temp;
      }
  };

总结

掌握C++的高级特性,如模板、异常处理和运算符重载,能够极大提升代码的灵活性与可读性。模板使得C++能够支持泛型编程,异常处理为程序提供了健壮的错误管理机制,而运算符重载则使得自定义类型能够更自然地进行操作。通过学习和应用这些特性,你将能够编写更强大和高效的C++程序。

发表回复 0

Your email address will not be published. Required fields are marked *