尽管我在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
因此,如果有人在比较这两种操作符,他们可能会将第一个操作符称为“隐式类型转换运算符”(或类似的名称),以便区分它与第二个操作符。
static_cast
这样的转换)或隐式的(通过标准转换序列或类中的非“explicit”构造函数和转换运算符)。 - David G