Mar*_*off 60
this是一个指针,*this是一个解除引用的指针.
如果你有一个返回的函数this,它将是一个指向当前对象的指针,而返回的函数*this将是当前对象的"克隆",在堆栈上分配 - 除非你指定了方法的返回类型返回参考.
一个简单的程序,显示复制操作和引用之间的区别:
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
1
1
2
3
Run Code Online (Sandbox Code Playgroud)
您可以看到,当我们操作本地对象的副本时,更改不会持久(因为它完全是一个不同的对象),但是对引用或指针进行操作会保留更改.
| 归档时间: |
|
| 查看次数: |
43300 次 |
| 最近记录: |