常量&, &和&&C++ 中成员函数的说明符

constamp; , amp; and amp;amp; specifiers for member functions in C++(常量amp;, amp;和amp;amp;C++ 中成员函数的说明符)

本文介绍了常量&, &和&&C++ 中成员函数的说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我正在阅读 boost 的 API::optional 并遇到了以下问题:

Recently I was reading through the API of boost::optional and came across the lines:

T const& operator *() const& ;
T&       operator *() & ;
T&&      operator *() && ;

我还编写了自己的程序,将成员函数定义为 const&、&和&&(请注意,我不是在谈论返回类型,而是在分号之前的说明符)并且它们似乎工作正常.

I also wrote my own program that defines member functions as const&, & and && (Note that I am not speaking about the return type, but the specifiers just before the semi-colons) and they seems to work fine.

我知道声明一个成员函数 const 是什么意思,但是谁能解释一下声明它是什么意思 const&, &和&&.

I know what it means to declare a member function const, but can anyone explain what it means to declare it const&, & and &&.

推荐答案

const& 表示,这个重载只会用于 const、non-const 和 lvalue 对象.

const& means, that this overload will be used only for const, non-const and lvalue object.

const A a = A();
*a;

& 表示,这个重载将只用于非常量对象.

& means, that this overload will be used only for non-const object.

A a;
*a;

&& 表示,这个重载将只用于右值对象.

&& means, that this overload will be used only for rvalue object.

*A();

有关 C++11 标准的此功能的更多信息,您可以阅读这篇文章 什么是*this"的右值引用?

for more information about this feature of C++11 standard you can read this post What is "rvalue reference for *this"?

这篇关于常量&, &和&&C++ 中成员函数的说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:常量&, &和&&C++ 中成员函数的说明符