【发布时间】:2018-04-18 02:09:57
【问题描述】:
以前有类似的问题,但我能找到的所有问题都提出了不同的问题:
-
static_cast vs. direct call to conversion operator - 相关但不同,讨论
static_cast<string>(x)与x.operator string() - 很多人在谈论
static_cast与 c 样式转换(通常将其称为函数样式转换)
在决定如何在类上实现显式转换时我应该考虑哪些事项?
在 c++11 中,我可以有一个显式的转换运算符:
class myClass {
public:
explicit operator std::string() const {
...
}
};
const myClass x{...};
std::string str = static_cast<std::string>(x);
或,我可以在toX():
class myClass {
public:
std::string toString() const {
...
}
};
const myClass x{...};
std::string str = x.toString();
我的一部分认为它们是相同的,但我的一部分认为我一定错过了一些场景或最佳实践指南。
授予static_cast 允许调用myClass::explicit operator std::string() 或std::string(myClass),但我专注于决定在myClass 内进行转换的地方,例如@987654332 @ 没有转换构造函数,因此这种区别不起作用。而且,它还允许在继承层次结构之间进行强制转换,但这在这里也不起作用。
【问题讨论】:
标签: c++11 casting static-cast