[英]Whats the difference between const int const& and const int& in C++?
[英]What is the difference between “const int& jj” and “int& const jj”?
我對這兩個感到困惑。 我知道C ++引用本身就是常量,一旦設置它們就無法更改為引用別的東西。
const int&
表示對const int
引用。 (類似地, int&
表示對非const int
引用。)
int& const
字面意思是const引用(對於非const int
),這在C ++中是無效的,因為引用本身不能是const限定的。
除非通過使用typedef-name([dcl.typedef],[temp.param])或decltype-specifier([dcl.type.simple])引入cv-qualifiers,否則Cv限定的引用是不正確的。 ,在這種情況下,cv限定符被忽略。
如你所說,引用本質上是不變的,一旦設置它們就不能被改為引用別的東西。 (我們不能在初始化后重新引用引用。)這意味着引用始終是“const”,然后const限定引用或const不合格引用實際上可能沒有意義。
應用於引用的const
限定符意味着您無法更改引用的值。 例如:
void foo(int& arg) {
arg = 1; // OK. The value passed by a caller will be changed in-place.
}
void foo(const int& arg) {
arg = 1; // Compilation error.
}
int& const jj
是編譯錯誤。
區別 :
const int& jj// means a reference to const int.
int& const jj // ill formed code that should trigger a compiler error
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.