c++函数如何返回这个

How do c++ functions return this

本文关键字:返回 函数 何返回 c++      更新时间:2023-10-16

我在stackoverflow上看到了这个例子,关于在c++函数中返回this返回" this "在c++中?,问题是如何处理this在c++中处理的返回。最好的答案是

class myclass {
  public:
  // Return by pointer needs const and non-const versions
     myclass* ReturnPointerToCurrentObject() { return this; }
     const myclass* ReturnPointerToCurrentObject() const { return this; }
  // Return by reference needs const and non-const versions
     myclass& ReturnReferenceToCurrentObject() { return *this; }
     const myclass& ReturnReferenceToCurrentObject() const { return *this; }
  // Return by value only needs one version.
     myclass ReturnCopyOfCurrentObject() const { return *this; }
};

现在我不明白为什么

myclass& ReturnReferenceToCurrentObject() { return *this; }

不能与

相同
myclass ReturnCopyOfCurrentObject() const { return *this; }

当我看到它的第一个例子返回一个引用,第二个返回一个解引用指针(值)?这两个函数怎么可能有相同的函数体呢?

当我看到它的第一个例子返回一个引用,第二个返回一个解引用指针(值)?

。第一个返回对调用它的对象的引用;第二个函数返回该对象的副本。

这两个函数怎么可能有相同的函数体?

因为从返回表达式*this到返回值的转换是隐式的。在第一种情况下,它被转换为引用;在第二种情况下,通过复制将其转换为一个值。

为了理解它们之间的区别,考虑一个更简单的例子会有所帮助。假设有两个独立的函数

int f()
{
   static int x;
   return x;
}
int & g()
{
   static int x;
   return x;
}

如你所见,这两个函数有相同的函数体和返回语句。

它们的区别在于,在第一种情况下返回静态变量x的副本,而在第二种情况下返回对静态变量x的引用。

在第二种情况下,你可以这样做,例如

g() = 10;

和函数体中定义的变量x将被更改。

在第一种情况下,你可能不会也不能做同样的事情。在本例中,创建了一个临时int对象,该对象是变量x的副本。