我可以防止与null与超载运算符==进行比较
Can I prevent comparison to NULL with overloaded operator==?
,假设我有一个我希望能够用指针构造或分配的字符串类,但是请使用explacitit std :: nullptr分配:
class String {
public:
String(const char *);
friend bool operator== (const String &, const char *);
friend bool operator!= (const String &, const char *);
// some important things left out
private:
String(std::nullptr_t);
}
目的是给出"错误:'operator ='是'字符串'的私人成员,如果我尝试编写" str = null",这可以帮助我识别旧代码库中的某些错误。显然,公共构造师也应该处理NULLPTR案件。此外,它可以帮助我确定一些类似的问题,例如" str = 0",编译器将其报告为模棱两可。
我的问题是 - 我可以对二进制比较运算符,操作员==和操作员做类似的操作!=?我希望编译器报告尝试与STD :: NULLPTR_T的尝试进行比较,该比较在我的代码库中也很常见。
每当您要禁止调用一个您可以附加= delete
的功能,该功能是在C 11:
friend bool operator==(const String&, std::nullptr_t) = delete;
friend bool operator!=(const String&, std::nullptr_t) = delete;
每当您尝试将您的类型与nullptr
进行比较时,您都会获得此编译器错误:
function "operator==(const String &, std::nullptr_t)" cannot be referenced -- it is a deleted function
相关文章:
- 为什么比较运算符如此快速
- 布尔比较运算符是如何在C++中工作的
- 关于 std::min, std::max 中的比较运算符的混淆
- 三向比较运算符成员与非成员实现
- 标准::可选枚举的比较运算符
- C++分数混合比较运算符错误
- 不能将重载比较运算符与 Catch 测试一起使用
- 重构使用动态强制转换的 std::set 的比较运算符
- 为什么我的比较运算符不比较我的点长和双精度值?
- 高效简单的结构比较运算符
- 如何实现 Boost.Hana 结构的相等比较运算符?
- 为什么sub_match和basic_string比较运算符使用额外的字符串副本实现?
- 是否可以在C++中使用三元运算符在 if 语句中选择比较运算符?
- 在priority_queue的自定义类中重载比较运算符
- 为什么C++容器之间存在比较运算符
- 尝试使用比较运算符对对象向量进行排序
- C++复合逻辑运算符不使用比较运算符
- C++:比较运算符>和字符串文本的意外结果
- 重载对象成员的比较运算符
- 比较运算符==中的对象指针