转自:https://blog.csdn.net/itcastcpp/article/details/5367049
(对原文有做修改,在Visual Studio 2017里调试通过)
VC++ 2010在C++里增加了一个特殊的新特性,SafeInt是一种安全数据类型,能够保证运算是安全的,使用安全数据类型能够规避软件异常,以及软件测试检测的常规性很多错误。
#include "stdafx.h"
#include <safeint.h>
#include <iostream>
using namespace std;
using namespace msl::utilities;
class CMySafeIntException : public SafeIntException
{
public:
static void SafeIntOnOverflow()
{
cout << "捕获SafeInt溢出异常!" << endl;
}
static void SafeIntOnDivZero()
{
cout << "捕获SafeInt被零除!" << endl;
}
};
int main(int argc, _TCHAR* argv[])
{
while (1)
{
unsigned int a, b;
cout << "输入前8位无符号整数: ";
cin >> a;
cin.ignore();
cout << "输入第二个8位无符号整数: ";
cin >> b;
cin.ignore();
// 添加两个变量
cout << "添加两个数字的8位整数:" << endl;
// 新增两个整数使用正常调用
unsigned __int8 i1 = a;
unsigned __int8 i2 = b;
cout << " 标准运算,结果=";
unsigned __int8 iResult = i1 + i2;
cout << (int)iResult << endl;
// 新增两个整数使用SafeInt对象
SafeInt<unsigned __int8, CMySafeIntException> si1(i1);
SafeInt<unsigned __int8, CMySafeIntException> si2(i2);
cout << " Using SafeInt objects, result=";
SafeInt<unsigned __int8, CMySafeIntException> siResult = si1 + si2;
cout << (int)siResult << endl;
// 整数相除
cout << endl << "整数相除:" << endl;
// 两个整数正常除法
cout << " 标准运算,结果=";
if (i2 != 0) // Prevent a crash!
{
iResult = i1 / i2;
cout << (int)iResult << endl;
}
else
cout << "中止因为除以零." << endl;
//两个整数除以使用SafeInt对象
cout << " 使用SafeInt对象, 结果=";
siResult = si1 / si2;
cout << (int)siResult << endl;
cout << endl << endl;
}
return 0;
}