[英]what happens when the function returning value is a pointer and the returning type is a reference in c++?
[英]Returning this pointer when the return type of a function is a reference (C++)
这里有一个非常相似的问题,但我不明白以下内容:
想象一下,我有一个用于 2D 数学向量的类,我想定义 setter 函数:
/** Setters **/
Vector2D& setX(double xcoor) {x = xcoor; return *this;}
Vector2D& setY(double ycoor) {y = ycoor; return *this;}
现在,“this”指针包含调用函数的实例的地址。
Vector2D VV(2,4);
VV.setX(1).setY(5);
在这种情况下,“this”具有 VV 实例的地址。 那么为什么不直接返回 this 而是返回 *this 呢?
在这种情况下,“this”具有 VV 实例的地址。
对。
那么为什么不直接返回 this 而是返回 *this 呢?
假设setX
将返回指针
Vector2D* setX(double xcoor) {x = xcoor; return this;}
//^--- no reference but pointer ---^
那么你的代码将是错误的:
Vector2D VV(2,4);
VV.setX(1).setY(5);
// ^ --------- error object has no class type, you cannot use .
“正确”将是VV.setX(1)->setY(5);
. 但是,没有理由使用指针。 我知道初学者可能难以理解,因为在教学中指针被过度使用。 大多数时候你并不关心指针或对象的内存地址。
您返回*this
,因为这就是启用链接所需的全部内容。 调用者有一个VV
对象,所以你返回的是VV
的引用,而不是其他东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.