gpt4 book ai didi

c++ - 无法创建两个继承自 std::logic_error 的自定义异常类

转载 作者:行者123 更新时间:2023-11-30 03:34:24 31 4
gpt4 key购买 nike

我的 cs 类任务是创建两个继承自 std::logic_error 的自定义异常类:OverflowingSwimmingPoolException 和 UnderflowingSwimmingPoolException。当尝试进行非法操作时,创建并抛出自定义异常,而不仅仅是打印错误消息。在您的驱动程序代码中包含 try...catch block 以捕获任何异常。

这是我的头文件的一部分:

    #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 类的私有(private)构造函数: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)是如何工作的。

最佳答案

错误很明显,与逻辑无关,也与您抛出异常的时间、地点和方式无关。这只是关于异常类本身和构造函数。

注意错误是怎么说你必须初始化父类的?您可以使用构造函数初始化列表来做到这一点,例如

OverflowingSwimmingPoolException ()
: std::logic_error("Some error message")
{}

std::logic_error 初始化中的错误信息是what函数将报告。

关于c++ - 无法创建两个继承自 std::logic_error 的自定义异常类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42062532/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com