从答案here。
class wrap {
public:
operator obj() const & { ... } //Copy from me.
operator obj() && { ... } //Move from me.
private:
obj data_;
};
我知道
&&
意味着当对象是右值引用时将调用该成员。但是,单个“&”号是什么意思?与没有“&”符号有何不同?
最佳答案
这意味着当对象是左值引用时将调用成员。
[C++11: 9.3.1/5]:
A non-static member function may be declared with a ref-qualifier (8.3.5); see 13.3.1.
[C++11: 13.3.1/4]:
For non-static member functions, the type of the implicit object parameter is
- “lvalue reference to cv
X
” for functions declared without a ref-qualifier or with the&
ref-qualifier- “rvalue reference to cv
X
” for functions declared with the&&
ref-qualifierwhere
X
is the class of which the function is a member and cv is the cv-qualification on the member function declaration. [..](and some more rules that I can't find)
如果没有ref限定符,则始终可以调用该函数,而不管通过其调用表达式的值类别是什么:
struct foo
{
void bar() {}
void bar1() & {}
void bar2() && {}
};
int main()
{
foo().bar(); // (always fine)
foo().bar1(); // doesn't compile because bar1() requires an lvalue
foo().bar2();
foo f;
f.bar(); // (always fine)
f.bar1();
f.bar2(); // doesn't compile because bar2() requires an rvalue
}
Live demo(感谢Praetorian)
关于c++ - 成员函数声明的参数列表后的单“&”号是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64180852/