我可以防止与null与超载运算符==进行比较

Can I prevent comparison to NULL with overloaded operator==?

本文关键字:比较 运算符 超载 null 我可以      更新时间:2023-10-16

,假设我有一个我希望能够用指针构造或分配的字符串类,但是请使用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