#虚函数
#include <iostream>
using namespace std;
class base //定义基类
{
public:
virtual void who() //虚函数声明
{
cout<<"this is the class of base !"<<endl;
}
};
class derive1: public base //定义派生类derive1
{
public:
void who() //重新定义虚函数
{
cout << "this is the class of derive1 !" << endl;
}
};
class derive2: public base //定义派生类derive2
{
public:
void who() //重新定义虚函数
{
cout << "this is the class of derive2 !" << endl;
}
};
int main()
{
base obj, *ptr; //声明基类对象obj、指针ptr
derive1 obj1; //声明派生类1的对象obj1
derive2 obj2; //声明派生类2的对象obj2
ptr= &obj; //基类指针指向基类对象
ptr -> who(); //调用基类成员函数
ptr = &obj1; //基类指针指向派生类1对象
ptr -> who(); //调用派生类1成员函数
ptr=&obj2; //基类指针指向派生类2对象
ptr -> who(); //调用派生类2成员函数
return 0;
}
#捕获异常
#include <iostream>
using namespace std;
int Div(int x,int y);
int main()
{
try
{
cout<<"5/2="<<Div(5,2)<<endl;
cout<<"8/0="<<Div(8,0)<<endl;
cout<<"7/1="<<Div(7,1)<<endl; //由于8/0抛出异常,所以7/1并没有运行
}
catch(int)
{
cout<<"except of deviding zero"<< endl;;
}
cout << "that is ok" << endl;
return 0;
}
int Div(int x,int y)
{
if(y==0)
{
throw y;
}
return x/y;
}