我對這兩者感到困惑。我知道C++的引用本質上是不變的,一旦設置,它們就不能被改變來引用別的東西。「const int&jj」和「int&const jj」有什麼區別?
6
A
回答
9
const int&
表示參考常量int
。 (類似地,int&
意味着參照非const int
。)
int& const
字面意思const引用(到非const int
),這是在C++中無效,因爲參考本身不能是常量限定。
$8.3.2/1 References [dcl.ref]是形成不良的,當cv修飾符 通過使用一個typedef名的介紹除了
CV-合格的引用([dcl.typedef], [temp.param])或decltype-specifier([dcl.type.simple]),在這種情況下,cv-qualifiers將被忽略。
正如你所說,引用本質上是恆定的,一旦設置,它們就不能被改變來引用別的東西。 (我們不能在初始化後重新引用引用。)這意味着引用總是「const」,那麼const限定的引用或者const-unqualified引用實際上可能沒有意義。
3
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
是一個編譯錯誤。
3
差異:
const int& jj// means a reference to const int.
int& const jj // ill formed code that should trigger a compiler error
相關問題
- 1. 爲什麼const int比const int&更快?
- 2. int const函數(參數),int函數(const參數)和int函數(參數)const之間的區別是什麼?
- 3. const int&x = 4和const int x = 4之間的區別
- 4. const int&value = 12和const int value = 12之間的區別;
- 5. static const和const有什麼區別?
- 6. 關於「int const * p」和「const int * p」
- 7. C++中的「const int」和「int」是否有區別?
- 8. 「int * const const * b」是什麼意思?
- 9. 「Int」和「const int的」在C++
- 10. static const char * const和static const char []之間有什麼區別?
- 11. 傳遞(int x)和(const int x)之間的區別
- 12. 函數參數的區別在C++中爲(const int&)和(int&a)
- 13. 返回值之間的區別int&和const int&
- 14. int [] x;有什麼區別?和int x [];?
- 15. 使用int [] []和int [,]有什麼區別?
- 16. int(1)和int(8)有什麼區別?
- 17. void(int)和void(*)(int)有什麼區別?
- 18. 第二個const在「const int const&someval」中做什麼?
- 19. 不允許在類型「const int ** const」和「int **」之間初始化,爲什麼?
- 20. var和const有什麼區別?
- 21. T&和T * const有什麼區別?
- 22. const int *&vs typedef int * IntPtr
- 23. 返回const int的*和回訪const int的*參考
- 24. 爲什麼{typedef int * PTR; const PTR p = #}不等於「const int * p = num」而是等於「int * const p = num」?
- 25. 「int * a = new int」和「int * a = new int()」有什麼區別?
- 26. swap(int&a,int&b)和swap(int * a,int * b)。有什麼區別?
- 27. int * const a = int const * b,對於obj(obj * const a = obj const * b)是否爲true?
- 28. (const char * str),(char const * str)和(char * const str)之間有什麼區別?
- 29. 轉換** const int的**
- 30. 分配const int的*
請問你的編譯器接受第二個變種? – juanchopanza
請指定哪個編譯器接受第二個變體。 – Angew
@HumamHelfawi這根本不是重複的。這個問題涉及'const int&'和'int const&',它們都是有效的(和等價的)形式。這個處理'const int&'和語法錯誤'int&const'。 – Angew