考虑这段代码:
#include <iostream>
using namespace std;
struct A {
void f() { cout << "A::f" << endl; }
void f() const { cout << "A::f const" << endl; }
};
struct B {
void f() & { cout << "B::f &" << endl; }
void f() const & { cout << "B::f const &" << endl; }
};
A getA() { return A{}; }
B getB() { return B{}; }
int main() {
getA().f();
getB().f();
}
打印出来的
A::f
B::f const &
对于 B
,选择 const 重载,而不是 non-const 重载。我想这意味着为 *this 指定左值 ref 限定符与根本不指定任何内容不同。这是为什么? “隐式这个参数”是否改变了类型并且 const 重载现在成为重载决议的更好候选者?
最佳答案
在这种情况下:
struct A {
void f() { cout << "A::f" << endl; }
void f() const { cout << "A::f const" << endl; }
};
getA().f();
对于 f
两种重载都是可行的,但非 const 是首选,因为它不需要转换。
但在这种情况下:
struct B {
void f() & { cout << "B::f &" << endl; }
void f() const & { cout << "B::f const &" << endl; }
};
getB().f();
第一个重载要求 this
是一个左值。但是在getB().f()
中,getB()
的结果是prvalue,不能绑定(bind)到non-const lvalue。所以这个重载是不可行的,没有被选中。
然而,第二个重载要求 this
是一个 const 左值,prvalue 可以绑定(bind)到该左值:这个重载是可行的并且由编译器选择。
关于c++ - 为什么在成员函数上为 *this 指定左值引用与不指定任何内容不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30393443/