【发布时间】:2017-11-28 05:29:31
【问题描述】:
我有一个以 int 作为参数的 some_func 函数调用。
int some_func(int);
class S {
public:
S(int v) {
a = v;
}
...
operator bool() const {
return true;
}
int a;
}; // class S doesn't define any "operator int"
S obj;
int x = some_func(obj); // some_func expected an int argument
在上面的代码中,some_func 需要 int 参数,但调用的是 S 类型的对象。因此它需要将其转换为“int”。
但是为什么它使用“operator bool”呢?它不应该产生编译错误,说明没有为类 S 指定正确的 int 转换方法吗?
如果我删除运算符 bool 定义,则程序无法编译并在 some_func 调用中给出有关参数类型不匹配的错误。
【问题讨论】:
-
A
bool值可隐式转换为int,其值为0(对于false)或1(对于true)。参见例如this implicit conversion reference(尤其是关于integral promotion的部分)了解更多信息。 -
我想我知道提升 bool 到 int 和隐式转换背后的一般想法。但这更微妙:存在从“S”到 int 的隐式转换(步骤 1),但隐式转换运算符不可用(showstopper 问题)。因此,正在使用另一个运算符(运算符 bool()),因为可以将“bool”提升为 int(步骤 2)。由于 showstopper 问题,无法进行第 1 步......(续......)
-
(..continued) 我认为 C++ 没有指定运算符 bool 而不是 bool 的什么提升(即当隐式转换运算符可以以某种方式用于进行“S”的转换时-> bool -> int 工作)。单独的积分促销在哪里完全涵盖了它?
-
为了防止隐式转换,请使用
explicit operator bool()- 自 C++11 起可用。
标签: c++ casting operator-overloading operators implicit-conversion