美文网首页
C++模板类&异常处理

C++模板类&异常处理

作者: 贝克街的猫大哥呀 | 来源:发表于2017-08-30 14:21 被阅读0次

    模板类类似JAVA中的泛型

    //模板类

    template<class T>

    class A{

       public:

       A(T a){

          this->a = a;

    }

       protected:

       T a;

    };

    //普通类继承模板类

    class B : public A{public:B(int a,int b) : A(a){

       this->b = b;

    }

       private:

       int b;

    };

    //模板类继承模板类

    template<class T>

    class C : public A<T>{

    public:C(T c, T a) : A(a){

    this->c = c;

    }

    protected:

    T c;

    };

    void main(){

    A a(6);

    system("pause");

    }

    如上面的几个例子,就理解成泛型吧

    C++ 异常处理,根据抛出的异常数据类型,进入到相应的catch块中

    void main(){

    try{

       int age = 300;

       if (age > 200){

          throw 9.8;

       }

    }

    catch (int a){

       cout << "int异常" << endl;

    }

    catch (char* b){

       cout << b << endl;

    }

    catch (...){

       cout << "未知异常" << endl;

    }

    system("pause");

    }

    如上,可以看出,C++抛异常,主要有三个关键字,cry,catch,throw

    而且与JAVA不同的是,catch可以是任意类型!throw也是任意类型,比如你throw一个char类型,那么如果catch里面也有char类型,就会走对应的catch,没有的话,就会走...类型!

    //throw 抛出函数外

    void mydiv(int a, int b){

    if (b == 0){

    throw "除数为零";

    }

    }

    void func(){

    try{

    mydiv(8, 0);

    }

    catch (char* a){

    throw a;

    }

    }

    void main(){

    try{

    func();

    }

    catch (char* a){

    cout << a << endl;

    }

    system("pause");

    }

    依然跟JAVA一样的。对应一下就行了

    自己创建一种异常:

    //标准异常(类似于JavaNullPointerException)

    class NullPointerException : public exception{

    public:

    NullPointerException(char* msg) : exception(msg){

    }

    };

    void mydiv(int a, int b){

    if (b > 10){

    throw out_of_range("超出范围");

    }

    else if (b == NULL){

    throw NullPointerException("为空");

    }

    else if (b == 0){

    throw invalid_argument("参数不合法");

    }

    }

    void main(){

    try{

    mydiv(8,NULL);

    }

    catch (out_of_range e1){

    cout << e1.what() << endl;

    }

    catch (NullPointerException& e2){

    cout << e2.what() << endl;

    }

    catch (...){

    }

    system("pause");

    }

    相关文章

      网友评论

          本文标题:C++模板类&异常处理

          本文链接:https://www.haomeiwen.com/subject/gvbzdxtx.html