C++ 我是否可以防止使用重载运算符==与NULL进行比较?

C++ 我是否可以防止使用重载运算符==与NULL进行比较?,c++,C++,假设我有一个字符串类,我希望能够使用指针构造或分配该类,但不允许使用显式std::nullptr分配进行编译: class String { public: String(const char *); friend bool operator== (const String &, const char *); friend bool operator!= (const String &, const char *); // some importa

假设我有一个字符串类,我希望能够使用指针构造或分配该类,但不允许使用显式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);
}
如果我试图写“str=NULL”,则给出“error:‘operator=’是‘String’的私有成员”,这有助于我识别旧代码库中的一些bug。显然,公共构造函数也应该处理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  

我打赌你可以只做
String(std::nullptr\u t)=删除
和类似的运算符(
friend bool operator==(const String&,std::nullptr\u t)=delete
,不要忘记另一个方向)或类似的运算符您是否尝试声明了另一个deleted/private运算符,它将nullptr\u t作为第二个参数而不是C字符串?