我阅读what-is-the-purpose-of-stdexceptionwhat并引用了std::exception
here
我需要从int
std::exception::what()
返回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; }
};
答案 0 :(得分:0)
你不能这样做。
如果你必须这样做:
<div class="row" >
<div class="col-4"><img src="http://via.placeholder.com/200.jpg?text=Placeholder"></div>
<div class="col-4"><img src="http://via.placeholder.com/200.jpg?text=Placeholder"></div>
<div class="col-4"><img src="http://via.placeholder.com/200.jpg?text=Placeholder"></div>
</div>
现在我们在缓冲区中存储并返回struct custom_error:std::exception {
const char* what() const throw() override final { return str.c_str(); }
explicit custom_error(std::string s):str(std::move(s)) {}
explicit custom_error(int x):custom_error(std::to_string(x)) {}
private:
std::string str;
};
的序列化描述,并根据请求返回指针。
转换回来:
int