我为我的 cs 类分配的任务是创建两个继承自 std::logic_error 的自定义异常类:OverflowingSwimmingPoolException 和 UnderflowingSwimmingPoolException。当尝试非法操作时,创建并抛出自定义异常,而不仅仅是打印错误消息。在驱动程序代码中包含 try...catch 块以捕获任何异常。
这是我的头文件的一部分:
#ifndef SWIMMINGPOOL_H
#define SWIMMINGPOOL_H
#include <stdexcept>
#include <iostream>
using namespace std;
namespace cs52
{
class OverflowingSwimmingPoolException: public logic_error
{
OverflowingSwimmingPoolException (){};
};
class UnderflowingSwimmingPoolException: public logic_error
{
UnderflowingSwimmingPoolException(){};
};
这是编译器在构造函数所在的行上说的:“cs52::UnderflowingSwimmingPoolException”的构造函数必须显式初始化没有默认构造函数的基类“std::logic_error”。
这就是我的实现文件中的内容:
#include "SwimmingPool.h"
#include <stdexcept>
#include <iostream>
using namespace std;
namespace cs52
{
SwimmingPool operator +(const SwimmingPool& pool1, const SwimmingPool& pool2) throw (OverflowingSwimmingPoolException, UnderflowingSwimmingPoolException)
{
SwimmingPool temp;
temp.mySize = pool1.mySize+pool2.mySize;
temp.myContents = pool1.myContents+pool2.myContents;
if (temp.myContents>temp.mySize)
throw OverflowingSwimmingPoolException();
return temp;
}
SwimmingPool operator -(const SwimmingPool& pool1, const SwimmingPool& pool2) throw (OverflowingSwimmingPoolException, UnderflowingSwimmingPoolException)
{
SwimmingPool temp;
temp.mySize= pool1.mySize-pool2.mySize;
temp.myContents= pool1.myContents-pool2.myContents;
if (temp.myContents>temp.mySize)
throw OverflowingSwimmingPoolException();
if (temp.myContents<0 || temp.mySize<0)
throw UnderflowingSwimmingPoolException();
return temp;
}
}
编译器在我抛出异常类的行中显示错误。它说:调用类 cs53:OverflowingSwimmimgPoolException 的私有构造函数。
我的驱动程序文件的一部分应该是这样的:
using namespace cs52;
try {
SwimmingPool badPool = smallOne - bigOne;
cout << "This should never happen..." << endl;
}
catch( UnderflowingSwimmingPoolException uspe ) {
cout << "working..." << endl;
}
catch( OverflowingSwimmingPoolException uspe ) {
cout << "This should never happen..." << endl;
}
我刚刚开始编写代码,所以我不太了解已经在库中创建的 std::logic_error 之类的类是如何工作的。