我理解'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();
}
Run Code Online (Sandbox Code Playgroud)
除了这个(人为的)例子之外,"this"指针的用例是什么?
感谢所有的答案.尽管我将橘子座的答案视为公认的答案,但这只是因为他获得了最多的投票.我必须说所有的答案都非常有用,让我更好地理解.
Don*_*ner 12
有时你想从运营商那里回来,比如 operator=
MyClass& operator=(const MyClass &rhs) {
// assign rhs into myself
return *this;
}
Run Code Online (Sandbox Code Playgroud)
如果您需要将指向当前对象的指针传递给另一个函数或返回它,这将非常有用.后者用于将字符串函数放在一起:
Obj* Obj::addProperty(std::string str) {
// do stuff
return this;
}
obj->addProperty("foo")->addProperty("bar")->addProperty("baz");
Run Code Online (Sandbox Code Playgroud)