到目前为止,据我了解,当定义一个指针变量时,我们正在RAM中为该变量分配空间。关于当前对象的C++指针和地址说明
int *p;
会在RAM中定义一个空间。然后我们使用'&变量'为该指针分配一个内存地址。
我找了一个例子上:*this vs this in C++ 的代码是:
#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;
}
我不明白是什么把*
运营商面前Foo* get_copy()
的目的和Foo* get_pointer()
一样。为什么我从Foo*
函数中删除*
而返回this
而不是*this
?
编辑:
另外,为什么是:
foo.get_copy().increment();
foo.print_value();
产生1不2?
'get_copy'的返回类型是错误的。它应该按值返回,而不是指针 - 'Foo get_copy()' –
Foo get_copy会产生一个错误,除非'this'更改为'* this'。 – eveo
'* this'正是它应该是。看看原始来源。你错了。 –