是否可以在 C++ 中覆盖(C 风格的)转换?
假设我有代码
double x = 42;
int k = (int)x;
我可以让第二行的类型转换执行我写的一些代码吗?有点像
// I don't know C++
// I have no idea if this has more syntax errors than words
operator (int)(double) {
std::cout << "casting from double to int" << std::endl;
}
我问的原因是因为问题 "Is there any way to get gcc or clang to warn on explicit casts?"以及我的建议。
最佳答案
§ 12.3.1/1 "Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions and are used for implicit type conversions (Clause 4), for initialization (8.5), and for explicit type conversions (5.4, 5.2.9)."
是的,我们可以进行转换,但前提是一侧或两侧是用户定义的类型,所以我们不能将 double
转换为 int
。
struct demostruct {
demostruct(int x) :data(x) {} //used for conversions from int to demostruct
operator int() {return data;} //used for conversions from demostruct to int
int data;
};
int main(int argc, char** argv) {
demostruct ds = argc; //conversion from int to demostruct
return ds; //conversion from demostruct to int
}
正如 Robᵩ 指出的那样,您可以将 explicit
关键字添加到这些转换函数中的任何一个,这需要用户使用 (demostruct)argc
或(int)ds
就像在您的代码中一样,而不是让它们隐式转换。如果您与同一类型相互转换,通常最好将其中一个或两个都设为 explicit
,否则您可能会遇到编译错误。
关于c++ - 强制转换是可覆盖的操作吗?如果是这样,如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10320282/