我写了一个更智能的指针类。并使下面的代码正确
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/