2014-05-23 36 views
-2

我試圖在MinGW中編寫這個簡單的代碼,但每次我嘗試將x設置爲負數時,它都會顯示消息「超出系統範圍!!」它應該顯示「x小於0」。我只是不明白爲什麼它一直只顯示消息....C++程序,但例外情況不起作用

#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; 
} 
+2

將unsigned int更改爲int!在setx中,sety函數。 –

+0

你已經定義了一個在SetX和SetY中無符號的符號,所以當你用-2調用它的時候,你實際上已經結束了真正的大數字。 –

回答

1

void Setx(unsigned a)採用參數作爲unsigned int。當您發送(帶符號)負數時,它會轉換爲unsigned int,併成爲一個很大的正數(>Max)。因此引發xOutOfSystemBounds異常,而不是xZero。你必須改變

void Setx(int a){ ...} 
1

那是因爲你用你的二傳手參數,根據定義,沒有負值的unsigned。將其更改爲int,它應該按預期行事。

相關問題