C++技术收集总结
1.类模板-template
- template 是声明类模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个,可以是类型参数 ,也可以是非类型参数。类型参数由关键字class或typename及其后面的标识符构成
template<class T> class test { .... }
template<typename T> class TestCls { public: T func(T a, T b) { //... } };
- 其中的类型参数名为虚拟的类型参数名,以后会被实际的类型名替代。如例子中的dataType将会被int,float,char等替代
- 例子
template <typename T> class calculate { public: T add(T a, T b); T subtract(T a, T b); T multiplication(T a, T b); T divide(T a, T b); }; template <typename T> T calculate<T>::add(T a, T b) { return a + b; } template <typename T> T calculate<T>::subtract(T a, T b) { return a - b; } template <typename T> T calculate<T>::multiplication(T a, T b) { return a * b; } template <typename T> T calculate<T>::divide(T a, T b) { return a / b; } int main(void) { calculate<int> op; printf("op.add(1, 2) = %d\n", op.add(1, 2)); printf("op.subtract(5, 2) = %d\n", op.subtract(5, 2)); printf("op.multiplication(12, 2) = %d\n", op.multiplication(12, 2)); printf("op.divide(8, 2) = %d\n", op.divide(8, 2)); return 0; }
2.C++异常处理
- try catch throw
- throw
- throw可以理解为人为地抛出自定义的异常类型,可以用于代码中符合某些条件时刻意地制造一些异常信息抛出给控制台处理
int fun(int & a, int & b) { if(b == 0) { throw "hello there have zero sorry\n"; //引发异常 } return a / b; }
- throw可以理解为人为地抛出自定义的异常类型,可以用于代码中符合某些条件时刻意地制造一些异常信息抛出给控制台处理
- try catch结构
- try块标识符其中特定的异常可能被激活的代码块,他后面跟一个或者多个catch块
- catch:类似于函数定义,但并不是函数定义,关键字catch表明这是给一个处理程序, 里面的const cahr *str 会接受throw传过来错误信息
#include <iostream> using std::cout; using std::cin; using std::cerr; int fun(int & a, int & b) { if (b == 0) { throw "hello there have zero sorry\n"; //引发异常 } return a / b; } int main5() { int a; int b; while (true) { cin >> a; cin >> b; try //try里面是可能引发异常代码块 { cout << " a / b = " << fun(a, b) << "\n"; } catch (const char *str) { cout << str; cerr << "除数为0\n"; //cerr不会到输出缓冲中 这样在紧急情况下也可以使用 } } system("pause"); }
#include <iostream> #include <exception> using namespace std; int main() { try { throw "error"; throw 1; } catch (const char *e) { cout << e << endl; } catch (int i) { cout << i << endl; } system("pause"); }
- throw