c++ - 在 C++ 中返回 "this"?

标签 c++ return this

在 Java 中,您可以简单地 return this 来获取当前对象。你如何在 C++ 中做到这一点?

Java:

class MyClass {

    MyClass example() {
        return this;
    }
}

最佳答案

嗯,首先,您不能从 void-returning 函数返回任何内容。

有三种方法可以返回提供对当前对象的访问的东西:通过指针、通过引用和通过值。

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; }
};

如前所述,这三种方式中的每一种都以略有不同的形式返回当前对象。使用哪一种取决于您需要哪种形式。

关于c++ - 在 C++ 中返回 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919330/

相关文章:

c++ - 为什么指针增量语句被优化掉了?

C# 子类返回未知类型(进一步 : from parent)

java - 我如何更改方法append(int n)中的 "this"?

C++ 指针和动态数组以及删除运算符

c++ - 括号后跟括号

java - 同一条线上的 if/else 条件不起作用

c - 用 C 求数组的中位数

jQuery 将 $(this) 传递给函数

PHP fatal error : Cannot use $this as parameter

c++ - 字符串文字不允许作为非类型模板参数