C++继承:构造函数中的字符串构造

C++ inheritance: string construction in constructor

本文关键字:字符串 继承 构造函数 C++      更新时间:2023-10-16

我现在正在学习C++,现在正在实现一个用于异常处理的示例程序。 主程序实现具有任意基数的数字系统。 我用函数virtual const char *what();做了一个类nums_exception : public std::exception

#include <stdexcept>
#include <sstream>
class Nums
{
public:
Nums() {}
unsigned int getBase() { return 2; }
};
class nums_exception: public std::exception
{
public:
nums_exception(Nums* obj, std::string errortext);
virtual ~nums_exception();
virtual const char *what() const noexcept;
const Nums *failObj();
private:
std::string errortext;
Nums *obj;
};
nums_exception::nums_exception(Nums *obj, std::string errortext)
: errortext(errortext)
, obj(obj)
{
}
nums_exception::~nums_exception() = default;
const char *nums_exception::what() const noexcept
{
if (this->errortext.size() == 0)
{
return "Nums exception!";
}
else
{
std::stringstream ret;
ret << "Nums exception at "
<< obj
<< " :"
<< this->errortext;
return ret.str().c_str();
}
}
// Now i derived  nums_bad_digit, which should look like this:
class nums_bad_digit: public nums_exception
{
public:
nums_bad_digit(Nums* obj, uint base, char digit);
virtual ~nums_bad_digit() override;
static std::string ERRORTEXT(Nums *obj, char digit);
private:
std::string errortext;
const uint base;
Nums *obj;
};
inline std::string nums_bad_digit::ERRORTEXT(Nums *obj, char digit)
{
return std::string(std::to_string(digit) + " not in alphabet for base " +
std::to_string(obj->getBase()) + '.');
}
nums_bad_digit::nums_bad_digit(Nums *obj, uint base, char digit)
: nums_exception(obj, ERRORTEXT(obj, digit))
, base(base)
{
}
nums_bad_digit::~nums_bad_digit() = default;
int main()
{
Nums n;
throw nums_bad_digit(&n, 42, 'x');
}

在这里,我尝试使用静态方法实现我的目标。

我想构造一个随时可以显示的错误消息,它说明我为什么抛出这个异常,然后将其传递给nums_exception构造函数。例如,nums_bad_digit::what(( 应该返回Nums_expection在0x777fff:"Q"不是以字母表表示基数 16

我还尝试了一个编译器宏...但无论我尝试什么 - 将其编写为普通代码都可以正常工作。但是当我想将字符串传递给nums_exception构造函数时,它总是会得到一个空字符串。

这里有几个问题。

  1. std::to_string不需要char.

    该参数可能会被提升为int,其值是输入的ASCII码(或你正在使用的任何代码(。所以'x'变得"120".不是你想要的。

    您应该改用std::string(1, digit)

    阅读您使用的函数的文档!至少,隔离测试程序的单元。

     

  2. what()返回一个const char*,但它指向的数据是死的。

    字符串流是本地的,字符串是临时的,因此此指针立即悬空。我会在构造函数中生成完整的字符串,并将其存储为成员,以便只要异常对象存在,它就会存在。

     

所以,这个:

nums_exception::nums_exception(Nums *obj, std::string errortext)
: obj(obj)
{
if (errortext.size() == 0)
{
this->errortext = "Nums exception!";
}
else
{
std::stringstream ret;
ret << "Nums exception at "
<< obj
<< " :"
<< errortext;
this->errortext = ret.str();
}
}

而这个:

const char *nums_exception::what() const noexcept
{
return errortext.c_str();
}

而这个:

inline std::string nums_bad_digit::ERRORTEXT(Nums *obj, char digit)
{
return std::string(1, digit) + " not in alphabet for base " +
std::to_string(obj->getBase()) + '.';
}

(现场演示(