赋值运算符c++NULL赋值
assignment operator c++ NULL assignment
我正在处理一个基本上运行良好的类,但我正在执行一些功能,我可能会让递归函数返回类类型的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问题,您可以在这里找到
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++中的赋值发生,尽管右侧出现异常
- 用C++中的sscanf赋值
- 为std::string的某个索引赋值
- 重载Singly Linked List中的赋值运算符
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- gtest_使用setargpointee在函数中赋值
- 在 Json::Value in JsonCpp 中赋值 [null]
- 赋值null中的不兼容类型
- C++-将null赋值给std::字符串
- 赋值运算符c++NULL赋值
- 赋值时执行char*,以null结束String
- 赋值给允许NULL成员的数组,而不使用堆
- 如果不为null,则为指针赋值
- 是否有必要在使用临时字符串值后将其赋值为null ?
- 我应该检查NULL在我的赋值操作符
- 是否应该将构造函数体中赋值的指针成员初始化为NULL ?
- 每次在链表中调用insert_node()函数时,Head都被赋值为Null
- while循环外的变量在重新赋值时变为NULL
- 通过解引用NULL指针来赋值引用