【发布时间】: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