c++函数如何返回这个
How do c++ functions return this
我在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的副本。
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 接收和返回函数指针的函数指针的类型?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++函数链返回函数
- 返回函数指针的函数的签名
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 如何在 C++ 中从 void 返回函数访问变量
- 返回函数中带有 2 个可选 ctor 的对象
- 如何在 c++ 中返回函数的结构向量
- 返回 C++ 函数中的引用
- 使用向量时,当返回函数更改时,无法看到输出
- 如何在递归中使用返回函数
- 返回函数模板的类型C++作为第二个模板参数
- 为什么静态指针返回函数中有一个"静态"键?
- 递归返回函数,在特殊情况下不返回
- 从类返回函数
- 从类成员函数返回函数指针
- 从返回函数中推断不存在的模板参数