【发布时间】:2022-01-17 07:51:30
【问题描述】:
根据 cppreference.com,显式转换函数不能用于隐式转换。例如,他们有这样的:
struct B
{
explicit B(int) { }
explicit B(int, int) { }
explicit operator bool() const { return true; }
};
int main()
{
...
if (b2) ; // OK: B::operator bool()
...
}
我原以为'if (b2)' 是隐式转换,因此无法使用显式转换函数。那么什么是不允许的隐式转换的例子呢?
【问题讨论】:
-
隐式转换在 cppreference.com 上有大量文档,请参阅:en.cppreference.com/w/cpp/language/implicit_conversion
-
显式 bool 运算符阻止的隐式转换是:
int x = b2; -
@paddy 那不是复制初始化而不是隐式转换吗?
标签: c++ if-statement operator-overloading explicit-conversion