在C ++中,对象可以为null吗?(In C++, can objects be null?)

编程入门 行业动态 更新时间:2024-10-26 12:21:33
在C ++中,对象可以为null吗?(In C++, can objects be null?)

这就是我所做的:我有一个简单的课程:

class Person{ public: Person(); } And in my main: int main() { Person myPer = NULL; }

这是不可能的,因为C ++不允许这样做,但是:

int main() { Person* perPtr = NULL; Person myPer = *perPtr; // corrected, it was &perPtr(typo error) before answers }

编译很好,因为我看到我能够有一个NULL对象。 那么它是否违反了只有指针在C ++中可以为null的规则? 或者C ++中有这样的规则吗? 第二个是我写完这段代码后,我添加了一个if语句,检查myPer是否为NULL,但这给了我错误。 所以它表明C ++并不真正喜欢NULL对象的想法,无论你做什么使对象为NULL ...

Here's what I have done: I've got a simple class:

class Person{ public: Person(); } And in my main: int main() { Person myPer = NULL; }

This is impossible since C++ does not allow that, however:

int main() { Person* perPtr = NULL; Person myPer = *perPtr; // corrected, it was &perPtr(typo error) before answers }

This compiles fine and as I see I did able to have a NULL object. So isn't it violating the rule that only pointers can be null in C++? Or is there such a rule in C++? 2nd one is after I wrote this code, I added a if statement checking whether myPer is NULL or not but that gave me error. So does it show that C++ does not really like the NULL object idea no matter what you do to make objects NULL...

最满意答案

对象不能为null,只有指针才能。 您的代码不正确且无法编译,因为它试图从指向Person的指针初始化Person 。 如果您要将代码更改为

Person* perPtr = NULL; Person myPer = *perPtr;

然后它会尝试从一个取消引用的空指针初始化一个Person ,这是一个未定义的行为(很可能是崩溃)。

如果你需要使用对象可能处于NULL状态的习语,你可以使用Boost.Optional :

boost::optional< Person > myPer = boost::none; if( myPer ) { myPer->do_something(); }

它是通常用指针完成的概括,除了它不使用动态分配。

Objects cannot be null, only pointers can. Your code is incorrect and does not compile, since its trying to initialize a Person from a pointer to a pointer to Person. If you were to change your code to

Person* perPtr = NULL; Person myPer = *perPtr;

then it would be trying to initialize a Person out of a dereferenced null pointer to a Person, which is undefined behavior (and most likely a crash).

If you need to use the idioms where an object could be in a NULL state, you could use Boost.Optional:

boost::optional< Person > myPer = boost::none; if( myPer ) { myPer->do_something(); }

It's a generalization of what is usually done with pointers, except it does not use dynamic allocation.

更多推荐

本文发布于:2023-08-04 10:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1414855.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   null   objects

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!