const 在C/C++的用法

const 在C/C++的用法

const的用法分為以下兩種:

1:在定義變量時使用:

總結:在使用const定義變量時,一定要進行初始化操作,在操作符(*,&)左邊的修飾的是指向的內容,在右邊的是本身。

a: const int a=100; 最簡單的用法,設定說明變數a是一個常數變數。

b: int const b=100; 與a功能相同。

c: const int *a=&b; 指向常數的指針,即指針本身的值是可以改變的,但指向的內容是不能改變的。

d: int const *a=&b; 與c功能相同。

e: int * const a = &b; 常數指針,即指針本身的值是不可改變的,但指向的內容是可改變的。

f: const int * const a = &b; 指向常數的常數指針,即指針本身與指向的內容都是不可改變的。

g: const int &a=100; 常數引用,即不能改變引用的值。

2:在函數用使用:

總結:在函數中使用const,情況與定義變數的情況大致相同。

a: void func(const int a); 做為參數使用,說明函數內是不能修改該參數的。

b: const int func(); 做為返回值使用,說明函數的返回值是不能被修改的。

c: int func() const; 常數函數,說明函數是不能修改該類別中成員的值的,只能用於類別的成員函數中。

(應用原則)

1.

先左由右,看左邊最近的是何種data type,若左邊沒有,則看右邊最近的。

2.

沿著*號劃一條線,

如果const位於*的左側,則const就是用來修飾指標所指向的變數,即指標指向為常量。

如果const位於*的右側,const就是修飾指標本身,即指標本身是常量。

範本

例一: const int * Constant1 --> const int (* Constant1)

例二: int const * Constant2 --> int const (* Constant2)

例三: int * const Constant3 --> (int *) const Constant3 --> const (int *) Constant3

例四: int const * const Constant4 --> const (int *) const Constant4

解答

例一 int值不可被修改

例二 int值不可被修改

例三 指標值不可被修改

例四 int值與指標值皆不可修改

在下面這邊做個總結

記憶體的位置可以變動,但是記憶體的內容不能變動

const Parent* pParent1 = new SubA();

記憶體的位置可以變動,但是記憶體的內容不能變動

Parent const *pParent2 = new SubA();

記憶體的內容可以變動,但是記憶體的位址不能變動

Parent* const pParent3 = new SubA();

記憶體的位址與內容都不能變動

const Parent* const pParent4 = new SubA();

記憶體的位置可以變動,但是記憶體的內容不能變動

const Parent const *pParent5 = new SubA();

相关推荐

安装摄像头做哪些资料
bet878365

安装摄像头做哪些资料

📅 07-01 👁️ 7087
通过手机APP查车辆违章,哪个软件比较好用?
mobile 365365051

通过手机APP查车辆违章,哪个软件比较好用?

📅 07-02 👁️ 5192
OPPO OPPO R7sm(4G)报价、参数、图片,联通智能3G合约手机