0
我读what-is-the-purpose-of-stdexceptionwhat和引用的std::exception
here从性病::例外比为const char *
定义我需要从std::exception::what()
返回int
,因为它是virtual
但我可以返回不同类型::什么()等不会被返回类型覆盖。我滚我自己的异常类
class BadLengthException : public std::exception
{
private:
int length;
const char* to_return;
public:
BadLengthException() = default;
BadLengthException(int new_length) : length(new_length) { to_return = new const char(length); }
~BadLengthException() = default;
const char* what() const throw() { return to_return; }
};
我将如何能够改变返回类型纯int
适合我的需求,使得
try
{
}
catch(BadLengthException bad_length)
{
std::cout << bad_length.what() <------- Got your int value
}
编辑我更改了代码。测试显示它提供了正确的值。我可以改进我所做的事吗?考虑到我必须总是返回const char*
?
class BadLengthException : public std::exception
{
private:
const size_t size = 2;
char ref_arr[5] = { '1','2','3','4','5' };
int length;
char* to_return;
public:
BadLengthException() = default;
BadLengthException(int new_length) : length(new_length)
{
to_return = (char*)malloc(size * sizeof(char));
to_return[0] = ref_arr[length - 1];
to_return[1] = '\0';
}
~BadLengthException() = default;
const char* what() const throw() override { return to_return; }
};
你不知道。为什么不只是添加一个额外的方法?然后,你的异常的捕手可以说'bad_length.length()'或者其他。 – GManNickG
@GManNickG在这个特殊的问题,我正在解决,预期的输出只限于'std :: exception :: what()' – Mushy
_I需要使用什么,因为我需要使用what_ ok – 2017-10-19 18:27:51