在 c++ 中正确定义"this"关键字?

Proper definition of "this" keyword in c++?

本文关键字:this 关键字 定义 c++      更新时间:2023-10-16

我正在学习OOP C++编程背后的一些理论。我们的教授为我们提供了一些示例问题,以便我们可以在考试前进行复习。你能看看,看看我对这个词的理解是否正确吗?我真的很感激任何建议。

The this keyword:
a) Inside a constructor, it is a reference to currently constructed object. (false)
b) In the method, it is a reference to the object for which it was called (true)
c) Inside the constructor it is a pointer to currently constructed object. (false)
d) In the method, it is a pointer to the object for which it was called. (false)

简单来说(这里不包括虚函数的复杂性(:

this是一个指针,指向构造的对象,这是传递给任何非静态成员函数的第一个参数。

举个例子,

class X  { void foo() {} } ;
X x;

当你做x.foo()时,foo(( 的第一个不可见参数等于&x。当你做x.foo()时,你实际上是在汇编级别做foo(&x)

构造函数在技术上(在程序集级别(只是一个函数,就像任何其他成员函数一样,唯一的区别是它在对象构造上被调用。它还像任何其他非静态成员一样采用 this 指针。

所以,你的问题,c(和d(是正确的。