我正在使用一个大部分工作正常的类,但我正在做一些功能,我可能有一个递归函数返回一个类类型的 NULL
指针作为控件,等等长话短说,它可能会为我的类对象分配一个 NULL
指针:
Thing& Thing::operator=(Thing * _other){
if (_other == NULL){
*this = NULL; // compiler throws here
return *this;
}
// does other assignment work
return *this;
}
我的编译器 VS2010 抛出 this
不是 I 值。那么如何将值设置为 NULL
,或者甚至可以从内部将项目设置为 NULL?
编辑:将 this
修改为 *this
尽管由于某种原因现在程序因对赋值运算符的无限调用而中断。不知道发生了什么
最佳答案
您正在尝试编写一个“可为空”的类。将“空”状态视为 Thing 实例可能处于的状态之一,不要将其与指针语义混淆。
一般方法是向您的类添加一个 bool 标志,以跟踪实例是否处于空状态。我会这样实现它:
class Thing
{
private:
bool m_null;
public:
void setnull() { m_null = true; }
bool isnull() const { return m_null; }
Thing() : m_null(true) {}
... // rest of class
};
现在默认的赋值运算符工作正常。
关于c++ - c++ NULL assignment 赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9663567/