c++ - C++中 'this'指针的用例

标签 c++ pointers

我理解“this”的含义,但看不到它的用例。

对于下面的例子,我应该告诉编译器参数是否与成员变量相同,我需要这个指针。

#include <iostream>

using namespace std;

class AAA {
    int x;
public:
    int hello(int x) { this->x = x;}
    int hello2(int y) {x = y;} // same as this->x = y
    int getx() {return x;}
};

int main()
{
   AAA a;
   a.hello(10); // x <- 10
   cout << a.getx();
   a.hello2(20); // x <- 20
   cout << a.getx();
}

除了这个(人为的)示例之外,“this”指针的用例是什么?

已添加

谢谢大家的回答。尽管我将 orangeoctopus 的回答作为接受的答案,但这只是因为他获得了最多的选票。我必须说所有的答案都非常有用,让我更好地理解。

最佳答案

有时你想从一个运算符返回你自己,比如operator=

MyClass& operator=(const MyClass &rhs) {
     // assign rhs into myself

     return *this;
}

关于c++ - C++中 'this'指针的用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3320622/

相关文章:

C++线程使用函数对象,如何调用多个析构函数而不调用构造函数?

c++ - 编译器如何知道 C++ constexpr 计算不会触发未定义的行为?

c - C 中带有指针的 string.h 和 strncpy

c++ - 两个方法声明都是 "pass by reference"吗?

c++ - STL 中有解引用迭代器吗?

iphone - 峰值滤波器有咔哒声和爆裂声

android - 如何在 Android NDK 的 Android.mk 文件中正确包含预建静态库?

c - 指向结构的指针。读取成员值的段错误

c - c中数组指针的解释?

c - 将固定大小的数组作为指针传递给函数时的警告