问题
How may I correct the following code in C++11:
const char *what() const noexcept override {
return "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) + ")";
}
As you can see I'm returning string
instead of const char*
but won't that be converrted automatically? and how to fix that?
Note: I want something to look like c++ code and not c using sprintf
for example
回答1:
but won't that be converrted automatically?
No.
and how to fix that?
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();
}
};
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)
+ ")"
)
{}
};
回答2:
It's not as simple because you are returning a temporary object which you are trying to convert into a pointer. You CAN do that by using
const char *what() const noexcept override {
return ("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) + ")").c_str();
}
but after converting the object will be destroyed and this will result in the actual data being deleted. Instead you can just copy the data.
const char* what()
{
std::string temp = "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) + ")";
char * p = new char[temp.size()+1]{};
strcpy(p,temp.data());
return p;
}
Just note that this is inefficient since you are creating and destroying and object and there is an extra copy which might be slow. Also you must remember to delete the char*
after using this function.
来源:https://stackoverflow.com/questions/62573397/returning-char-instead-of-string