异常不工作的c++程序

c++ program with exceptions not working

本文关键字:c++ 程序 工作 异常      更新时间:2023-10-16

我尝试在MinGW中编写这个简单的代码,但每次我尝试将x设置为负数时,它都会显示消息"超出系统界限!!"并且它应该显示"x低于0"。我只是不明白为什么它只显示这个消息....

    #include <iostream>
    #define Max 80
    #define Min 20
    using namespace std;
    class Punct
    {
protected:
    int x,y;
public:
    class xZero{};
    class xOutOfSystemBounds{};
    Punct (unsigned a, unsigned b)
    {
        x=a;
        y=b;
    }
    unsigned Getx()
    {
        return x;
    }
    unsigned Gety()
    {
        return y;
    }
    void Setx( unsigned a )
    {
        if( a<0 )
            throw xZero();
                else
                if(( a>Max || a<Min ) && a>0 )
                    throw xOutOfSystemBounds();
                    else
                    x=a;
    }
    void Sety( unsigned a )
    {
        if( a<0 )
            throw xZero();
                else
                if( a>Max || a<Min )
                    throw xOutOfSystemBounds();
                    else
                    y=a;
    }
};
int main()
{
    Punct w(4,29);
    try
    {
        w.Setx(-2);
        cout<<"noul x:>"<<w.Getx()<<'n';
    }
    catch( Punct::xZero )
    {
        cout<<"x is lower than 0"<<'n';
    }
    catch( Punct::xOutOfSystemBounds )
    {
        cout<<"out of system bounds!!"<<'n';
    }
    catch( ... )
    {
        cout<<"Expresie necunoscuta!"<<'n';
    }
    system("PAUSE");
    return 0;
 }

void Setx( unsigned a )取参数为unsigned int。当你发送一个(有符号的)负数时,它被转换成unsigned int,变成一个大的正数(> Max)。因此抛出的异常是xOutOfSystemBounds,而不是xZero。你必须改变

void Setx( int a ){ ...}

这是因为您在setter参数中使用了unsigned,根据定义,该参数没有负值。将其更改为int,它应该像预期的那样运行。