1 模板类
template<class T> class A{
public:
A(T a){
this->a = a;
}
protected:
T a;
};
普通类继承模板类
class B :public A<int>{
public:
B(int a,int b):A<int>(a){
this->b = b;
}
private:
int b;
};
调用
void main(){
B(3,4);
system("pause");
}
初始化B类一定要先初始化A的构造方法。如果不初始化,如下:
模板类继承模板类
template <class T>
class C : public A<T>{
public:
C(T c, T a) :A<T>(a){
this->c = c;
}
protected:
T c;
};
调用
void main(){
C<int>a(6,4);
system("pause");
}
2 异常处理
catch会根据抛出的异常类型,来捕获相应的数据类型。
void main(){
try{
int age = 300;
if (age>200){
throw 9.3;
}
}
catch(int a){
cout << "int异常" << endl;
}
catch (char* name){
cout << name << endl;
}
catch (...){ //表示未知异常
cout << "未知异常" << endl;
}
system("pause");
}
打印结果
未知异常
异常处理 抛出到方法外
void mydiv(int a,int b){
if (b==0){
throw "除数为零";
}
}
void func(){
try{
mydiv(3, 0);
}
catch (char* a){
throw a;
}
}
void main(){
try{
func();
}
catch (char* a){
cout << a << endl;
}
system("pause");
}
首先异常在mydiv()方法中被抛出,然后在func()中被catch,最终在main方法中被catch。
抛出对象 异常类
class MyException{
};
void mydiv(int a,int b){
if (b==0){
throw MyException();
//throw new MyException;//不要抛出异常指针,不然还要调用delete方法去释放
}
}
void main(){
try{
mydiv(3,0);
}
catch (MyException& e){
cout << "引用类型" << endl;
}
catch (MyException* e){
cout << "指针类型" << endl;
}
system("pause");
}
抛出标准异常
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 (NullPointerException& e){
cout << e.what() << endl;
}
catch (...){
}
system("pause");
}
打印结果
为空
内部类异常
class Err{
public:
class MyException{
public:
MyException(){
}
};
};
void mydiv(int a,int b){
if (b>10){
throw Err::MyException();
}
}
void main(){
try{
mydiv(8,20);
}
catch (Err::MyException& e){
cout << "接受到内部类异常"<< endl;
}
catch (...){
}
system("pause");
}
打印结果
接受到内部类异常