gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:00:36 26 4
gpt4 key购买 nike

我理解“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com