c++ - 如果类对象需要在 C++ 中转换为 int,为什么会调用 "operator bool()"?

标签 c++ casting operator-overloading operators implicit-conversion

我有一个以 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 转换方法吗?

如果我删除 operator bool 定义,则程序不会编译并给出有关 some_func 调用中参数类型不匹配的错误。

最佳答案

C++ 具有隐式转换。通过定义转换运算符 operator bool(),您已使 S 可隐式转换为 bool。这是用户定义的转换。一次转换可以由一系列转换组成(其中只有一个可以由用户定义)。

虽然没有直接从 S 到 int 的转换,但是有一个从 bool 到 int 的内置转换(这是一个整数提升,true 转换为 1,false 转换为 0)。因此转换序列 S -> bool -> int 是有效的,因此 S 可以隐式转换为 int。


附言。如果您想在调用该函数时阻止从 bool 的隐式转换,您可以声明一个已删除的重载,重载决议将首选该重载:

int some_func(bool) = delete;

关于c++ - 如果类对象需要在 C++ 中转换为 int,为什么会调用 "operator bool()"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741679/

相关文章:

c++ - 从字节指针读取位的差异

c++ - 在 lxml2 中找不到 -lz 库

casting - 如何在多态中使用boost::smart_ptr?

c# - 在调用 Dispose() 之前转换为 IDisposable

c++ - 一次处理所有传递的重载

c++ - 初始化字符串 vector 数组时出错

c++ - 如何在无需重新编译的情况下使 Git 提交哈希在 C++ 代码中可用?

c++ - 在附加之前将 "number 0"转换为 char

c++ - 为什么返回 *this 会导致无限循环?

C++ 级联 operator[] 到 operator() 参数列表?