pmg*_*pmg 4 c++ overriding casting
是否可以在 C++ 中覆盖(C 风格)强制转换?
假设我有代码
double x = 42;
int k = (int)x;
Run Code Online (Sandbox Code Playgroud)
我可以让第二行中的演员执行我写的一些代码吗?就像是
// 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;
}
Run Code Online (Sandbox Code Playgroud)
我问的原因是因为“有没有办法让 gcc 或 clang 对显式转换发出警告?” 和我的建议。
第 12.3.1/1 节“类对象的类型转换可以由构造函数和转换函数指定。这些转换称为用户定义的转换,用于隐式类型转换(第 4 条)、初始化(8.5)和用于显式类型转换(5.4、5.2.9)。”
是的,我们可以进行转换,但前提是一侧或两侧是用户定义的类型,因此我们无法为double
to进行转换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
}
Run Code Online (Sandbox Code Playgroud)
作为罗布? 指出,您可以将explicit
关键字添加到这些转换函数中的任何一个,这要求用户在代码中使用 a(demostruct)argc
或(int)ds
like显式转换它们,而不是让它们隐式转换。如果您在同一类型之间进行转换,通常最好将其中一个或两个都设置为explicit
,否则可能会出现编译错误。