C++:23 再议const的用法(下)
生活随笔
收集整理的這篇文章主要介紹了
C++:23 再议const的用法(下)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
上一篇文章折騰了一波粉絲,那么這一篇文章稍微溫柔一些。
我主要開始說如何正確使用const
1.不能將const 修飾的任何對象、引用和指針作為賦值表達式的左值。
const int cx=100;
const int & rcx=cx;
const int * pcx=&cx;
cx=200; //error
rcx=200; //error
*pcx=200; //error
Int& a =100; //error
2.const 類型的對象不能直接被non-const 類型的別名所引用。
(1)不能將const 類型的對象傳遞給non-const 類型的引用。
const int cx=100;
int & rx=cx; //error
(2)不能將const 類型的實參傳遞給形參為non-const 類型引用的函數。
void f(int a)
{}
void g(int & ra)
{}
const int cx=100;
f(cx); //ok
g(cx); //error
(3)不能將const 類型的對象作為non-const 類型引用的函數返回值。
int & f(const int & rca)
{
return rca; //error
}
int x=100;
f(x);
3.可以使用const 類型別名引用non-const 對象。
總結
以上是生活随笔為你收集整理的C++:23 再议const的用法(下)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PRML(2)--绪论(下)模型选择、纬
- 下一篇: C++(16)--运算符重载(自定义In