异常不工作的c++程序
c++ program with exceptions not working
我尝试在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
,它应该像预期的那样运行。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 如何在c++程序中找到函数的地址