z50g_18_12_20@G 發表於 2018-12-21 11:49

C++ const的用法討論

常看到的是如
const int Function(xxxxx)
代表返回的值是不可被更改

int Function(xxxx) const
代表在Function內的變數是不可被變更的

int Function(const std::string &xxxx)
代表傳入的std::string為位址且其內的值不可被改扁

有其他人有較簡易明瞭的資訊 也可提出分享

daber 發表於 2018-12-21 16:53

class A{   …void function()const; //常數成員函數,不改變物件的成員變數。也不能呼叫類中任何非const成員函數。}
class A::function() const {....}
--------------------另外:int function(const char *str);// 常數字元陣列,表示 str 的內容不會再函式內被改變,所以可以用雙引號代入常數字串 "aaabbbcc" ,如果不加 const ,須載入的必須為字元陣列的變數



gygy23 發表於 2018-12-22 13:59

const 用於定值,為了避免有誤用參數。
頁: [1]
查看完整版本: C++ const的用法討論