C++ const

來源:互聯網
上載者:User

標籤:未定義   ali   odi   初始化   儲存   etc   改變   int   無法   

1.const 修飾變數
int base = 0;// 定義常量(類中的唯讀變數 只能且必須 在初始化列表中initialize)// const常量只是給出了對應的記憶體位址,而不是象#define一樣給出的是立即數,所以const定義的常量// 在程式運行過程中只有一份拷貝,而#define定義的常量在記憶體中有若干個拷貝。const int a1 = 1; // 編譯器可以對它進行型別安全檢查(宏常量只是簡單的替換,可能會產生意料不到的錯誤)int const a2 = 1;// 修飾指標int * const b1 = &base;// 同時修飾值和指標int const * const c1 = &base;const int * const c2 = &base; // const修飾記憶:關鍵字左邊的,本身在最左邊時修飾右邊

 

2.const 修飾函數(參數、傳回值、函數本身)
class Code{    CString m_code;public:    Code() {}    ~Code() {}    const CString* getCode(const CString& src)const;    void setCode(const CString& src);};
void Code::setCode(const CString& src){ m_code = src;}const CString* Code::getCode(const CString& src) const{ // error //src = result; // const修飾的變數唯讀,且在唯讀函數內 //m_code = src; // const修飾的類成員函數 不能修改成員 //setCode(src); // const修飾的類成員函數 只能調用唯讀成員函數 return &m_code;}

getCode()函數的傳回值必須用 const CString* re = code.getCode( _T("GB1001") );  或者寫成 auto re = code.getCode( _T("GB1001") );

 

這種唯讀保證是編譯器做的限制,少數情況下要在唯讀函數內修改對象的屬性,可以這麼做:

const CString* Code::getCode(const CString& src) const{     // 1.mutable關鍵字修飾 mutable int value;    // 2.繞過編譯器的限制    Code* p = (Code*)this; // 關鍵在於this強轉為Code*    p->setCode(src);    return &m_code;}
const和函數重載
void Code::fun(int a)const // 可以重載,根據對象是否唯讀區別{}void Code::fun(int a){}void Code::fun(const int a) // 無法重載{}void Code::fun(int a){}

 

3.const修飾對象

const修飾的對象只能訪問 類中的唯讀函數,不能修改變數。較好的設計應該是用const限定方法,不限定對象,類中的屬性只能通過方法 Get() 或 Set() 

 

4.唯讀迭代器

 

5.const和智能指標

 

6.const 在C語言和C++中的不同

C++中的const一般被看成編譯期的常量,不為const分配空間, 只是在編譯的時候將值儲存在符號表中,並在適當的時候摺合在代碼中
C++中, 是否為const分配空間要看具體情況,若加上關鍵字extern或者取const變數地址,編譯器就要為const分配儲存空間
C語言中的const是一個不能被改變的普通變數,會佔用儲存空間

const int size = 10;int array[size] = { 0 }; // C語言中error: 編譯器不知道編譯時間的值(數組下標必須明確)

 

7.const_cast 關鍵字
// const_cast用來移除變數的const或volatile限定符:// 使用const_cast再寫的後果是未定義的,const_cast的目的並不是為了讓你去修改一個本身被定義為const的值,// 因為這樣做的後果是無法預期的。const_cast的目的是修改一些指標/引用的許可權,// 如果我們原本無法通過這些指標/引用修改某塊記憶體的值,現在你可以了。const int a = 1;//int* temp = a; // errorint* pa1 = const_cast<int*>(&a); // 去除const限制int* pa2 = (int*)&a; // 傳統方式去除const限定*pa1 = 10;int modify1 = a; // 1,這裡直接被替換成常量運算式,不再從地址中取值(const常量引入的初衷是替代#define)*pa2 = 100;int modify2 = a; // 1

 

C++ const

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.