【问题标题】:c++ program with exceptions not working带有异常的c ++程序不起作用
【发布时间】:2014-05-23 05:22:20
【问题描述】:

我尝试在 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;
 }

【问题讨论】:

  • 将无符号整数更改为整数!!!在 setx、sety 函数中。
  • 你已经在 SetX 和 SetY 中定义了 a 是无符号的,所以当你用 -2 调用它时,你实际上会得到一个非常大的数字。

标签: c++ exception error-handling


【解决方案1】:

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

void Setx( int a ){ ...}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2016-04-10
      • 2020-06-10
      • 1970-01-01
      • 2016-08-23
      • 2018-07-08
      • 2022-11-28
      相关资源
      最近更新 更多