*this vs this in C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2750316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
*this vs this in C++
提问by Mark Rushakoff
I understand what this
does, but what is the difference between *this
and this
?
我明白是什么this
意思,但是*this
和之间有什么区别this
?
Yes, I have Googled and read over *this
in my text book, but I just don't get it...
是的,我*this
在我的教科书中搜索并阅读了谷歌,但我就是不明白......
回答by Mark Rushakoff
this
is a pointer, and *this
is a dereferenced pointer.
this
是一个指针,并且*this
是一个解除引用的指针。
If you had a function that returned this
, it would be a pointer to the current object, while a function that returned *this
would be a "clone" of the current object, allocated on the stack -- unlessyou have specified the return type of the method to return a reference.
如果您有一个返回 的函数this
,它将是指向当前对象的指针,而返回的函数*this
将是当前对象的“克隆”,分配在堆栈上——除非您指定了该方法的返回类型返回一个引用。
A simple program that shows the difference between operating on copies and references:
一个简单的程序,显示了操作副本和引用之间的区别:
#include <iostream>
class Foo
{
public:
Foo()
{
this->value = 0;
}
Foo get_copy()
{
return *this;
}
Foo& get_copy_as_reference()
{
return *this;
}
Foo* get_pointer()
{
return this;
}
void increment()
{
this->value++;
}
void print_value()
{
std::cout << this->value << std::endl;
}
private:
int value;
};
int main()
{
Foo foo;
foo.increment();
foo.print_value();
foo.get_copy().increment();
foo.print_value();
foo.get_copy_as_reference().increment();
foo.print_value();
foo.get_pointer()->increment();
foo.print_value();
return 0;
}
Output:
输出:
1
1
2
3
You can see that when we operate on a copyof our local object, the changes don't persist (because it's a different object entirely), but operating on a reference or pointer doespersist the changes.
您可以看到,当我们对本地对象的副本进行操作时,更改不会持久化(因为它完全是不同的对象),但对引用或指针的操作确实会持久化更改。
回答by Marcelo Cantos
this
is a pointer to the instance of the class. *this
is a referenceto the same. They are different in the same way that int* i_ptr
and int& i_ref
are different.
this
是指向类实例的指针。*this
是对相同的引用。它们以相同的方式不同,int* i_ptr
并且int& i_ref
不同。
回答by Chris Hafey
There is no real difference, this->foo()
is the same as (*this).foo()
.
没有真正的区别,this->foo()
是一样的(*this).foo()
。