C++回顾

版权声明: https://blog.csdn.net/moon_sky1999/article/details/82828867
/*常量引用+模板函数*/
namespace example1 {
    template<class T>
    T max(const T &a, const T &b) {
        return a < b ? b : a;
    }

    template<class T>
    T max(const T &a, const T &b, const T &c) {
        return max(a, max(b, c));
    }

    template<class Ta, class Tb>
    Ta get_sum(const Ta &a, const Ta &b) {
        return a + b;
    }
}
/*异常处理*/
namespace example2 {
    void test1() {
        try {
            int a, b;
            std::cin >> a >> b;
            if (b == 0)
                throw "error";
            std::cout << a / b << std::endl;
        }
        catch (...) {
            std::cout << "error!" << std::endl;
            return;
        }
    }

    void test2() {
        int *x;
        try { x = new int[100]; }
        catch (std::bad_alloc e) {
            std::cerr << "error!" << std::endl;
            exit(1);
        }
        delete[] x;
    }
}

猜你喜欢

转载自blog.csdn.net/moon_sky1999/article/details/82828867