在C ++中正确定义“ this”关键字?

我正在学习有关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)
评论
  • Burne
    Burne 回复

    简单地说:

    The this is a pointer that points to the object that was constructed and this the first parameter passed to any non static member function.

    例如

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

    When you do x.foo(), foo()'s first invisible parameter is equal to &x. The constructor techically is just a function like any other member function, the only difference is that it's called on object construction. It also takes the this pointer like any other non-static member.

    因此,您的问题c)和d)是正确的。

  • 宝贝不哭
    宝贝不哭 回复

    From the C++ standard:

    关键字this是一个prvalue表达式,其值是   在其上调用成员函数的对象。它可以   出现在以下上下文中:      1)体内任何非静态成员函数,包括成员   初始化列表      2)在非静态成员的声明中   在(可选)cv限定词序列之后的任何地方起作用,   包括动态异常规范(不建议使用),noexcept   规范以及尾随返回类型      3)在默认成员初始化器内

    Basically, all of your statements are true except this is not a reference but a pointer.