简体   繁体   English

C++ 中的返回值 vs 指针 vs 引用

[英]Return value vs pointer vs reference in C++

I saw this question on StackOverflow:我在 StackOverflow 上看到了这个问题:

return "this" in C++?在 C++ 中返回“这个”?

And a question came to my mind - what's the difference between these three?我想到了一个问题——这三个有什么区别?

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

Take a close look at the following:仔细看看以下内容:

int i = 10;
int* ptr = &i;
int& ref = i;
int copy = i;

If you understand the differences between the last three lines, you can extend that understanding to the member functions in your posted code.如果您了解最后三行之间的区别,您可以将这种理解扩展到您发布的代码中的成员函数。 If you don't understand the differences, it will be best to learn these basic concepts from a good textbook .如果您不了解这些差异,最好从一本好的教科书中学习这些基本概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM