尽管我看到 C++ 教程中广泛使用术语 implicit casting
来表示这样一个事实,即当您将某种类型分配给另一种类型时,类型的转换将自动(隐式)完成,但我经常听说应该叫implicit conversion
而不是implicit casting
。谁能告诉我这两者的区别?
最佳答案
正常情况下应该叫隐式转换。
几乎唯一一次您可能会看到有人合理地谈论“隐式强制转换”是在谈论类中的强制转换运算符时。例如:
class T {
int x;
public:
T (int x) : x(x) {}
operator int() { return x; }
};
有些人称其为强制转换运算符,这是一种可以隐式调用的运算符。从 C++11 开始,您可以向其添加 explicit
:
class T {
int x;
public:
T (int x) : x(x) {}
explicit operator int() { return x; }
};
...防止隐式调用。例如,这意味着:
T t(10);
int x = t; // works with the first version, not the second
int y = static_cast<int>(t); // works with either version
因此,如果有人比较/对比这两者,他们可能会将第一个称为“隐式转换运算符”(或类似的东西)以将其与第二个区分开来。
关于c++ - 它叫 "implicit casting"还是 "implicit conversion"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007435/