爲什麼編譯?C++常量在參考上丟失
struct A {};
struct B {
B(A& _a) : a(_a) {}
A &a;
};
void f1(A&) {}
void f2(const B &b) { f1(b.a); }
int main() {
A a;
B b{a};
f2(b);
return 0;
}
f2()b是const,所以我的理解是b.a也應該是const。但它編譯並且編譯器允許調用f1()。
替換爲'A &';'在結構B中用'A a'它不再有效。 現在F1()b.a確實是常量:
invalid initialization of reference of type 'A&' from expression of type 'const A'
請幫我理解這...謝謝。
錯誤:'const'限定符不能應用於'A&' – Jarek
誰說的? (在什麼情況下?)是的,它是[完全多餘](https://isocpp.org/wiki/faq/const-correctness#const-ref-nonsense)。無論如何,它更像是思想實驗;) –