好的,这是一个非常基本的问题。
我可以在 C++ 方法/成员函数中使用 this 指针的真正原因是什么?
换句话说:当我有
class foo
{
void bar();
}
为什么可以使用
void foo::bar()
{
this->...
}
我可以想象两种可能:
- 它是某种自动创建的成员变量吗
- 它作为参数传递给每个方法(因此每个方法都由该参数自动扩展)
最佳答案
正如其他一些人所指出的,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
isX*
. If the member function is declared const, the type of this isconst X*
, if the member function is declared volatile, the type of this isvolatile X*
, and if the member function is declared const volatile, the type of this isconst 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/