conversion-operator
参考文档
user-defined conversion function - cppreference.com
The Safe Bool Idiom - 知乎
一般形式为operator type() const
, 比如:
operator int() const; operator bool() const; operator AA() const;
自定义类型转换
struct To { To() = default; To(const struct From&) {} // converting constructor }; struct From { operator To() const {return To();} // conversion function }; int main() { From f; To t1(f); // direct-initialization: calls the constructor // Note: if converting constructor is not available, implicit copy constructor // will be selected, and conversion function will be called to prepare its argument // To t2 = f; // copy-initialization: ambiguous // Note: if conversion function is from a non-const type, e.g. // From::operator To();, it will be selected instead of the ctor in this case To t3 = static_cast<To>(f); // direct-initialization: calls the constructor const To& r = f; // reference-initialization: ambiguous }
为什么operator bool()
需要用explicit修饰?
c++ - Why does declaring an operator bool() const
member overload the [] operator? - Stack Overflow
The operator is coming from the built-in subscript operator which treats expressions A[B]
as *(A + B)
.
This results in the evaluation of *(1 + "wut")
=> 'u'
, which then causes the if
condition to pass, as 'u'
is a non-zero value.
Declare your member as explicit operator bool() to prevent your type from being implicitly converted to other integral types.
#include <iostream> using namespace std; struct Test { operator bool() const { return true; } }; int main(int argc, char** argv) { Test test; if (test) cout << "Object test is true\n"; if (test["wut"]) std::cout << "Success (test[\"wut\"])\n"; } // Output: // Object test is true // Success (test["wut"])
一个operator bool()
的坑
c++ - Why is my "explicit operator bool()" not called? - Stack Overflow
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!