c++ - 重载运算符 !=

标签 c++ operator-overloading smart-pointers

我写了一个更智能的指针类。并使下面的代码正确

ZhjSmartPointer<int> a(new int);  
assert(a != NULL); 

我像这样重载 != 运算符:

bool operator !=(T *ptr) const; 

然而,这会导致这样的编译错误:

ZhjSmartPointer.h:132: note: candidate 1: bool ZhjSmartPointer::operator!=(T*) const [with T = Test] test.cpp:41: note: candidate 2: operator!=(int, int)

我对如何将 ZhjSmartPointer 转换为 int 感到困惑

SmartPointer类的代码是这样的:

template <typename T>
class ZhjSmartPointer {
public:
    ZhjSmartPointer();
    explicit ZhjSmartPointer(T *ptr);

    ZhjSmartPointer(const ZhjSmartPointer &smartPtr);
    ZhjSmartPointer &operator =(const ZhjSmartPointer &smartPtr);
    ~ZhjSmartPointer();

    operator bool() const;
    T &operator *() const;
    T *operator ->() const;
    bool operator ==(const ZhjSmartPointer &smartPtr) const;
    bool operator !=(const ZhjSmartPointer &smartPtr) const;

    bool operator ==(T *ptr) const;
    bool operator !=(T *ptr) const;

private:
    void copyPtr(const ZhjSmartPointer &smartPtr);
    void deletePtr();
    T *ptr_;
    size_t *refCnt_;
};

我猜是因为我重载了'bool'运算符,'ZhjSmartPointer -> bool -> int'导致了这个问题。这是对的吗?

抱歉,这只是编译警告,不是错误。有人建议我不要用parameter(T *)重载!=,毕竟我们已经重载了'bool'。写这样的代码就可以了:
ZhjSmartPointer a(new int);
如果一个) { …………
}

最佳答案

在C++中NULL被定义为0,而不是(void*)0,事实上大部分教科书都会告诉你使用0 而不是 NULL

如果你使用的是 C++11,你应该顺便使用 nullptr


您的问题确实是 bool 隐式转换。要解决您的问题,请改用 operator not (!)。

关于c++ - 重载运算符 !=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14994961/

相关文章:

c++ - 通过引用返回 `std::shared_ptr`

V8 中的 Javascript 等价物?

c++ - 汇编中的内联 C++ 方法

operator-overloading - 如何为不同类型的参数实现一个结构的 Fn 特性?

c++ - 隐式转换运算符优先级

Swift 中类似 Python 的运算符重载

C++ - 指针和 'smart pointers'

c++ - 从 IStream 加载 PNG 时 GDI+ 崩溃

c++ - 访问嵌套模板类型

c++ - 重构代码以使用 Boost 共享指针