虚函数及捕获异常练习

#虚函数
#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;
}
此条目发表在C++分类目录。将固定链接加入收藏夹。

发表评论

邮箱地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Protected with IP Blacklist CloudIP Blacklist Cloud