1 摘要
this is a pointer, and *this is a dereferenced pointer.
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 – unless you have specified the return type of the method to return a reference.
- 翻译:this返回的是指针,this返回的是去引用化的指针。return this,即返回当前指向的对象(类型为T* 或者T&);return *this,即返回当前对象的克隆(类型为T),除非你强调返回的是一个引用。
2 详细部分
- return this 返回的是指针,return * this返回的是该指针指向的对象;而返回类型为Foo,此时会创建Foo类型的对象【与 * this 类型相同】,并将 *this 的值赋给新的Foo类型对象;
Foo get_copy() { return *this; }
- return * this返回的是该指针指向的对象,返回类型是引用,即引用*this指针指向的对象;
Foo& get_copy_as_reference() { return *this; }
- return this 返回的就是指针,因此用指向Foo类型的指针(Foo*)接收;
Foo* get_pointer() { return this; }
3 完整代码:
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;
}
1
1
2
3