【发布时间】:2018-11-25 21:21:04
【问题描述】:
在“编程:使用 C++ 的原则和实践”中,“第 8.5.7 节参数检查和转换”中给出了以下示例作为如何正确转换类型的证据,但从未明确解释您为什么要使用 int()与static_cast<int>() 相比,从double 转换为int。但是,我仍然不清楚 static_cast<int>() 与 int() 的好处。
void ff(int x);
void gg(double y) {
ff(y); // how would you know if this makes sense?
int x=y; //how would you know if this makes sense?
}
void ggg(double x) {
int x1 = x; // truncate x
int x2 = int(x);
int x3 = static_cast<int>(x); // very explicit conversion (17.8)
ff(x1);
ff(x2);
ff(x3);
ff(x); // truncate x
ff(int(x));
ff(static_cast<int>(x)); // very explicit conversion (17.8)
}
我检查了第 17.8 节,但仍然没有找到关于这个主题的清晰内容。有人可以帮忙吗?我正在寻找一种将 static_cast 与函数样式转换进行比较的解决方案。
【问题讨论】:
-
@cbuchart 答案不包括功能符号转换。
标签: c++ type-conversion explicit-conversion