gpt4 book ai didi

引用、对象和指针之间的 C++ 区别

转载 作者:IT老高 更新时间:2023-10-28 22:22:53 26 4
gpt4 key购买 nike

这是一个 OOP 高级类(class)的考试题,用 C++ 教授(在 TAU 大学,本学期):

问:C++ 指针和引用有什么区别?

A.  A reference is the entire object while a pointer is only the address of it.B.  The same meaning, and difference is only in syntax and usage.C.  The syntax used to access the object.D.  Pointers are simple address to the object while a reference uses the virtual table.

哪个是正确答案?

类(class)老师声称 A 是正确的,并且对对象的引用实际上就是对象本身。那是对的吗?我意识到访问引用等同于访问对象本身,但是,在破坏引用时,我们不会破坏对象本身。引用是对象的替代名称,但说引用==对象为真?

顺便说一句,讲师给了the following link to an faq as support for his claim ,引用:

"Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object."

但是,我仍然认为这是不正确的。

最佳答案

他们都错了。

reference本质上是另一个对象的同义词。在内部,它通常被实现为一个指针,但它的语法就好像它是它所引用的对象一样。

指针是一个单独的对象,它存储它所指向的对象的内存地址(如果它不指向一个对象,则为 0)。

可以说引用是它所引用的对象(它肯定会这样做),但事实并非如此。如果引用超出范围,则它所引用的对象不会被破坏,因此引用不是对象。

关于引用、对象和指针之间的 C++ 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3224155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com