赋值运算符c++NULL赋值

assignment operator c++ NULL assignment

本文关键字:赋值 c++NULL 赋值运算符      更新时间:2023-10-16

我正在处理一个基本上运行良好的类,但我正在执行一些功能,我可能会让递归函数返回类类型的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?

EDIT:将this修改为*this,但由于某种原因,现在程序会因对赋值运算符的无限调用而中断。不知道发生了什么

您正试图编写一个"可为null"的类。将"null"状态视为Thing实例可以处于的状态之一,不要将其与指针语义混淆。

一般的方法是在类中添加一个布尔标志,用于跟踪实例是否处于null状态。我会这样实现:

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
};

现在默认的赋值操作符工作正常。

不能直接为this指针设置值。因此

this = NULL;

在语义和句法上都是错误的。

您可以使用异常来检查_other是否为NULL。例如:

class null_object_exception : public virtual exception {};
...
if (_other == NULL) throw null_object_exception();

执行NULL分配:

Thing the_thing, other_thing;
try { the_thing = &other_thing; }
catch( const null_object_exception& e ) { the_thing = NULL; }

Thing类的成员变量是什么?如果你想显示对象在某种程度上没有值或没有初始化,你最好指定fileds 0(对于整数)和null(对于指针)等,而不是指定常量"this"。

简短回答,不,您不能在C++中分配给this

更长的答案;为了调用赋值运算符,您必须具有这样的构造;

MyObject a;
a = NULL;    // can change the content of `a` but not which object the name `a` refers to.

如果你正在考虑这个结构;

MyObject *a;
a = NULL;

赋值运算符甚至不会被调用,因为它是对象上的运算符,而不是指针。在不定义赋值运算符的情况下,为指针a赋值将起作用。

不能分配给this

此外,您应该通过const引用来接受您的论点,因此Thing& operator= (const Thing& other)

C++-faq标签中有一个关于运算符重载的SO问题,您可以在这里找到