C++ 引用、对象和指针之间的区别 [英] C++ difference between reference, objects and pointers

查看:30
本文介绍了C++ 引用、对象和指针之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 OOP 高级课程考试中的一道题,用 C++ 教授(在 TAU 大学,本学期):

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

<前>A. 引用是整个对象,而指针只是它的地址.B. 意思相同,区别仅在于语法和用法.C. 用于访问对象的语法.D. 指针是指向对象的简单地址,而引用使用虚拟表.

正确答案是什么?

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

顺便说一句,讲师提供了以下链接到常见问题解答以支持他的主张,引用:

<块引用>

"重要提示:即使引用通常使用底层程序集中的地址语言,请不要想到一个参考作为一个有趣的指针到一个对象.参考是对象.它不是指向对象,也不是对象的副本.它是对象."

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

解决方案

他们都错了.

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

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

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

This is a question from an exam in an advanced course in OOP, taught in C++ (in TAU university, this semester):

Q: What is the difference between a C++ pointer and a reference?

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.

Which is the correct answer?

The course teacher claims that A is the correct one, and that a reference to an object is, in fact, the object itself. Is that correct? I realize that accessing the reference is equivalent to accessing the object itself, however, when destructing a reference, we do not destruct the object itself. A reference is an alternative name for the object, but saying that reference==object true?

BTW, the lecturer gave the following link to an faq as support for his claim, a quote:

"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."

But still, I believe this is incorrect.

解决方案

They're all wrong.

A reference is essentially a synonym for another object. Internally, it is often implemented as a pointer, but it has the syntax as if it were the object it refers to.

A pointer is a separate object that stores the memory address of the object it points to (or 0 if it doesn't point to an object).

You could say that the reference is the object that it refers to (it certainly acts that way), but it is not. If a reference goes out of scope then the object it refers to is not destructed, so the reference is not the object.

这篇关于C++ 引用、对象和指针之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆