close

const這個keyword真的很複雜,

別的語言可能就在前面加上const,

但是呢,C++的const組合真的是多到炸掉,

在哪裡都要加const搞的人都看不懂,

還記得我第一次看到,書上有很多種寫法,就很想要搞清楚,

那時沒有注意到 const *p 、 *const p 的差別,到頭來還是一知半解,

不過說真的,在這個地方不建議花太多時間,效益太低了,

但也不能不懂,所以我會講一些平常會遇到的,

至於太奇葩的就略過吧。╮(╯_╰)╭


我先簡單講加上const就代表此值"無法更改",

先看線上面的例子,

這比較好理解,

const int 就代表不能改值,

*const 就代表不能指向別人,

兩個都有就都不能做。

 

線下的比較麻煩,剛開始會跟上面的搞混,

簡單說 int const *p,你可以指向別人,

但不能改值,就跟 const int一樣,

這個是要比較注意的地方。  

#include <iostream>

int main(){

    int a1 = 10;

    const int a2 = 11;

    const int *p1 = &a1; //*p1=66  fasle,  p1=&2 true 

    int *const p2 = &a1; //*p2=66  true,  p2=&2 false

    const int *const p3 = &a1; //*p3=66  fasle,  p3=&2 false

    //------------------------

    const int *p4 = &a1; //*p4=66  fasle,  p4=&2 true
 
    int const *p5 = &a1; //*p5=66  fasle,  p5=&2 true

    const int const *p6 = &a1; //*p6=66  fasle,  p6=&2 true

    return 0;
}

 

還有一種是添加在function,可以看到下面的例子,

只要是const function 就只能 顯示、迭代...等等,不能有"="的動作,切記切記

還有宣告const function 的位置是在void printb() 後面。

class test{

public:
    int a;
    int *p;
    void printb() const{
        //p = &a; error
        //a=45;  error
        std::cout<<"hello b"<<std::endl;
    }

};

 

之後有看到更多const的用法在寫上來。ლ(・´ェ`・ლ)

 

arrow
arrow
    創作者介紹
    創作者 讀書小天地 的頭像
    讀書小天地

    書籍分享天地

    讀書小天地 發表在 痞客邦 留言(0) 人氣()