更新时间:2023-02-06 13:02:41
但是那不会自动转换吗?
but won't that be converrted automatically?
否.
以及如何解决?
将字符串存储为成员,然后在 what
中调用 c_str()
.示例:
Store the string as a member, and call c_str()
in what
. Example:
struct descriptive_name : std::exception {
std::string msg;
descriptive_name(
int mat1_width,
int mat1_height,
int mat2_width,
int mat2_height)
: msg(
"Mtm matrix error: Dimension mismatch: ("
+ std::to_string(mat1_height)
+ ","
+ std::to_string(mat1_width)
+ ") ("
+ std::to_string(mat2_height)
+ ","
+ std::to_string(mat2_width)
+ ")"
)
{}
const char *what() const noexcept override {
return msg.c_str();
}
};
甚至更好:从 std :: runtime_error
继承,不要覆盖 what
,并使用消息字符串初始化基类.示例:
Even better: Inherit from std::runtime_error
, don't override what
, and initialise the base class with the message string. Example:
struct descriptive_name : std::runtime_error {
descriptive_name(
int mat1_width,
int mat1_height,
int mat2_width,
int mat2_height)
: std::runtime_error(
"Mtm matrix error: Dimension mismatch: ("
+ std::to_string(mat1_height)
+ ","
+ std::to_string(mat1_width)
+ ") ("
+ std::to_string(mat2_height)
+ ","
+ std::to_string(mat2_width)
+ ")"
)
{}
};