我試圖在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;
}
將unsigned int更改爲int!在setx中,sety函數。 –
你已經定義了一個在SetX和SetY中無符號的符號,所以當你用-2調用它的時候,你實際上已經結束了真正的大數字。 –