问题描述
是否可以在C ++中重写(C风格)强制转换?
Is it possible to override (C-style) casts in C++?
假设我有代码
double x = 42;
int k = (int)x;
我可以在第二行执行一些代码我写的演员吗?像
Can I make the cast in the second line execute some code I wrote? Something like
// 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;
}
推荐答案
是的,我们可以进行转换,或者两边都是用户定义的类型,所以我们不能为 double
到 int
p>
Yes, we can make conversions, but only if one or both sides is a user-defined type, so we can't make one for 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
}
Robᵩ指出, 显式
关键字到这些转换函数,这需要用户显式转换他们与(demostruct)argc
(int)ds
就像在代码中,而不是让它们隐式转换。如果你转换为和从同一类型,通常最好有一个或两个作为显式
,否则你可能会得到编译错误。
As Robᵩ pointed out, you can add the explicit
keyword to either of those conversion functions, which requires the user to explicitly cast them with a (demostruct)argc
or (int)ds
like in your code, instead of having them implicitly convert. If you convert to and from the same type, it's usually best to have one or both as explicit
, otherwise you might get compilation errors.
这篇关于是casts overridable操作?如果是,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!