c++ - 为什么我可以在方法中使用 'this'

标签 c++ methods

好的,这是一个非常基本的问题。

我可以在 C++ 方法/成员函数中使用 this 指针的真正原因是什么?

换句话说:当我有

class foo
{
    void bar();
}

为什么可以使用

void foo::bar()
{
    this->...
}

我可以想象两种可能:

  1. 它是某种自动创建的成员变量吗
  2. 它作为参数传递给每个方法(因此每个方法都由该参数自动扩展)

最佳答案

正如其他一些人所指出的,this 关键字通常由编译器通过将其作为第一个参数传递给成员函数来实现,因此成员函数:void SomeClass::func(int a, int b) 内部看起来像:void SomeClass::func(SomeClass* this, int a, int b),const 版本如下: void SomeClass::func(const SomeClass* this, int a, int b)

然而,我觉得最有趣的是,它不是标准强制执行的。

C++ 标准说(§ 9.3.2 ad 1):

In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*. [ Note: thus in a const member function, the object for which the function is called is accessed through a const access path. —end note ]

这很有趣,因为与许多其他事物一样,C++ ABI大部分留给编译器,这可能很麻烦。因此,虽然对于大多数编译器(甚至可能是全部)来说确实如此,this 是通过作为第一个参数隐式传递来实现的,但标准并不能保证它,因此可以以不同的方式实现由一个新的编译器,尽管我怀疑它会发生。

关于c++ - 为什么我可以在方法中使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33477090/

相关文章:

c++ - MongoDB C++ 驱动断言失败

c++ - 什么时候函数应该使用 cstrings 而不是字符串? (C++)

c++ - 使用 Qt5 在 Windows 上获取 HWND(来自 WId)

c++ - 我的构造函数主体中的简单指针语法问题

c++ - 以编程方式检查年份是否更改的最有效方法是什么

JavaScript IE 错误 : unexpected call to method or property access

java - 使用一个类中的方法到另一个类中

java - 从其他类 Android Java 调用静态方法

java - 使用另一个类中的方法将数字添加到数组中?

java - vector 、点、战舰、2D