考虑这段代码,
struct A {};
struct B { B(const A&) {} };
void f(B)
{
cout << "f()"<<endl;
}
void g(A &a)
{
cout << "g()" <<endl;
f(a); //a is implicitly converted into B.
}
int main()
{
A a;
g(a);
}
这编译得很好,运行良好。但是,如果我更改f(B)为f(B&),它不会编译。如果我写f(const B&),它再次编译良好,运行良好。原因和道理是什么?
概括:
void f(B); //okay
void f(B&); //error
void f(const B&); //okay
我想听听语言规范中每种情况的原因、理由和参考资料。当然,函数签名本身并没有错。而是A隐式转换为Band const B&,但不转换为B&, 并导致编译错误。