this
是成员函数隐式接收的对象/实例的 const ptr,那么 return *this
如何返回引用?
据我所知,一个指向变量的指针解引用意味着它拥有它的内存地址,所以 return *this
应该返回被这个 const 指针解引用的值,这是什么?一个对象?
另外,为什么你不能做这样的事情:
Calc cCalc;
cCalc.Add(5).Sub(3).Mult(4);
没有所有成员函数返回 *this
?
我想知道指针和引用如何处理对象/实例。
最佳答案
让我们试着理清:
this is a const ptr to the object/instance which a member function receive implicitly
成员函数确实隐含地接收了这个指针。类型是 T* 或 const T*,具体取决于成员函数签名——您将 const 放在 () 之后的尾部放置 const 关键字。
so how does return *this returns a reference ?
*this 取消对指针的引用,从而分别创建类型为 T 或 const T 的左值。如果您的问题是您如何在 const 函数中从 *this 获取 T&,而您没有得到答案,那么该尝试将是格式错误的代码。
As of what I know , a pointer dereferencing to a variable means it holds it's memory address , so return *this should return value dereferenced by this const pointer which is what? An object?
*这表示实例。它是左值表达式。因此,您可以再次获取它的地址(提供与此相同的内容),或者可以将它绑定(bind)到一个引用——包括返回的情况。
如果函数返回 Calc 而不是 Calc& 或返回与 *this 不同的对象,则实际上可以完成您显示的链接——但是计算结果最终会在那个地方结束。不在您期望的位置:在 cCalc 中。
按照目前的情况,当三个函数都返回*this时,首先Add在this中取&cCalc,返回cCalc。下一次调用 Sub 的情况相同。还有乘法。
关于c++ - *return 如何隐式返回引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17128271/