C++ - definition of (*this)

C++ - definition of (*this)

本文关键字:this of definition C++      更新时间:2023-10-16

我有一个用c++编写的代码,我不知道这个代码应该做什么。我试过在论坛上搜索,但我仍然很困惑。有人能帮我定义一下这个代码吗?

inline void normalize() {
       const float inv_length = 1.0f / get_length();
       (*this) *= inv_length;
}

(*this)语法真的让我很困惑,它指的是返回值吗?如果你有更多的时间,你能用Java重写它吗?

this是指向调用成员函数的当前对象的指针。

*this只是取消引用那个指针,所以它是对那个对象的引用。


重写为Java:

void normalize() {
    final float inv_length = 1.0f / get_length();
    this.multiply(inv_length); // Since there is no operator overloading in Java, this had to be converted to a method.
    // Note that the "this." above is optional.
}

虽然this关键字在C++中为您提供了一个指针(因为引用是在this之后添加到C++的),但正如Nicky C.所指出的那样,相同的关键字在Java中为您带来了一个引用

(this)是一个指针,即存储变量的地址。它前面的星号(*)表示这是一个指针。

(*this) *= inv_length;

与相同

(*this) = (*this) * inv_length;

(*this)是指向的任何(this)的值

您的语句所做的是将存储在指针中的值乘以inv_length。