C++ const 限定符

來源:互聯網
上載者:User

標籤:class   編譯   ons   pointer   turn   沒有   code   編譯器   效率   

#include<stdlib.h>#include<iostream>int MAX(const int a, const int b);/**    const限定符:*    1. 定義:限定一個變數不允許被改變,產生靜態作用*    2. 分類:*        (1)    頂層const:限定變數本身不可改變*            例:    const int number;*                int *const pointer;**        (2)    底層const:限定變數所指向的對象不可改變,所有的引用都是底層const*            例:    const int *pointer;*                const int &quotation;*    3. 用法:*        (1)    定義常量**        (2)    保護被修飾的東西**        (3)    很方便的進行參數的調整和修改**        (4)    為函數重載提供了一個參考    (***)**        (5)    節省空間的,避免不必要的記憶體配置*            const定義常量從彙編的角度來看,只是給出了對應的記憶體位址,而不是象#define一樣給出的是立即數,所以,const定義的常量在程式運行過程中只有一份拷貝,而#define定義的常量在記憶體中有若干個拷貝**        (6)    提高效率*            編譯器通常不為普通const常量分配儲存空間,而是將它們儲存在符號表中,這使得它成為一個編譯期間的常量,沒有了儲存與讀記憶體的操作,使得它的效率也很高*/int main(){    /*    *    1. 定義:限定一個變數不允許被改變,產生靜態作用    *    2. 分類:    *        (1)    頂層const:限定變數本身不可改變    *        (2)    底層const:限定變數所指向的對象不可改變,所有的引用都是底層const    */    const int num_1 = 10;    //num_1 = 20;    //錯誤:num_first 被const 修飾,不可改變    const int *num_pointer_1 = &num_1;    num_pointer_1 += 8;    //正確:底層const ,限定指標所指的變數不可變    std::cout << num_pointer_1 << *num_pointer_1 << std::endl;    const int &num_reference = num_1;    //num_reference = 20;    //錯誤:使用const 修飾引用變數時,都是底層const    std::cout << std::endl;    std::cout << std::endl;    /*    *    3.用法:    *        (2)    便於進行類型檢查(與宏進行比較)    */    int num_3_1 = 12;    int num_3_2 = 32;    std::cout << "MAX(num_3_1, num_3_2) = " << MAX(num_3_1, num_3_2) << std::endl;    std::cout << "MAX(NUM_DE_1, NUM_DE_1) = " << MAX(NUM_DE_1, NUM_DE_1) << std::endl;    }int MAX(const int a, const int b){    return a > b ? a : b;}

 

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.