[英]using const to prevent datatype changing and value changing
使用 const 有區別嗎:
無法更改數據類型,但可以更改 a 或 b 的值
int add(const int a, const int b);
可以更改數據類型但不能更改 a 或 b 的值
int add(int const a, int const b);
無法更改數據類型,也無法更改 a 或 b 的值
int add(const int const a, const int const b);
非常感謝您的任何建議
const int 和 int const 的區別:
int const 和 const int 是一樣的。
但是指針有區別:
char sz[3] = "hi";
//const char* allows you to change what is pointed to,
//but not change the memory at the address that is pointed to
const char *p = sz;
p = "pi";//ok
//p[0] = 'p';//not valid, bad
//char * const allows you to change the memory at the address that is
//pointed to, but not change what is pointed to.
char * const q = sz;
//q = "pi";//not valid, bad
q[0] = 'p';//ok
//or disallow both:
const char * const r = sz;
//r = "pi";//not valid, bad
//r[0] = 'p';//not valid, bad
大多數時候你想使用 const char *。
更改變量的類型:
您無法更改變量的類型,但可以將變量的地址重新解釋為另一種類型。 為此,您使用強制轉換。
我不知道應該如何更改 C++ 中變量的數據類型...
'const' 是一個 promise 您對編譯器所做的關於不修改值的操作。 當您不這樣做時它會抱怨(可能在此過程中發現 z 錯誤)。 它還有助於它進行各種優化。
以下是一些 const 示例及其含義:
f ( const int a )
f 不能改變 'a' 的值。
f ( int const a )
一樣的,但是寫的很奇怪
f ( const int const a )
沒有任何意義,gcc 告訴我“重復常量”
f ( const int * pa )
f 不能改變 pa 指向的值
f ( int * const pa )
f 不能改變指針的值
f ( const int * const pa )
f 不能改變指針的值,也不能改變指向的值
f ( int a ) const
成員 function f 不能修改其 object
希望它能讓事情更清楚..
您永遠不能更改任何變量的數據類型。 如果你有const int
它總是與int const
相同。 雖然,對於 function 聲明,有一些特殊情況。
實際上,
int add(const int a, const int b);
和
int add(int a, int b);
或者其中的任何const
組合都聲明相同的 function。 在外面,它們都是相同的,實際上也都是相同的類型。 它只對函數的定義很重要。 如果你不放 const
int add(int a, int b) { a++; /* possible, increment the parameter */ }
您可以更改參數(在此示例中是傳遞的 arguments 的副本)。 但是如果你放 const,參數將在 function 定義中為 const
int add(int const a, int const b) {
a++; // bug, a is a constant integer!
}
為什么為 function 聲明寫 const 與否無關緊要? 因為參數將被復制,所以無論如何它不會對調用者和調用者 arguments 產生任何影響,因此。 建議使用以下樣式,在標題中,聲明不帶 const 的函數
int add(int a, int b);
然后,在定義中,如果您希望參數為 const,請將 const 放入。
#include "add.hpp"
// remember, const int and int const is the same. we could have written
// int add(const int a, const int b); too
int add(int const a, int const b) { return a + b; }
成員函數的計數相同
struct foo {
void f(int);
};
void foo::f(int const a) { ... }
請注意,我們只討論了直接影響參數的 const 的 const。 在使用引用或指針時,還有其他 const 會影響 constness。 這些常量不容忽視,實際上很重要。
const int x;
是相同的
int const x;
關鍵字的順序不相關。 這也適用於unsigned等關鍵字:
const unsigned int x;
int unsigned const x;
但是,此規則不適用於指針,因為星號 (*) 不是關鍵字,而是運算符。 所以前面的規則不適用:
const int *x;
不一樣:
int * const x;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.