使用const来防止数据类型更改和值更改

ant*_*009 1 c++ const

使用const之间有区别吗:

无法更改数据类型但可以更改a或b的值

int add(const int a, const int b);
Run Code Online (Sandbox Code Playgroud)

可以更改数据类型但不能更改a或b的值

int add(int const a, int const b);
Run Code Online (Sandbox Code Playgroud)

无法更改数据类型且无法更改a或b的值

int add(const int const a, const int const b);
Run Code Online (Sandbox Code Playgroud)

非常感谢任何建议

Bri*_*ndy 8

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
Run Code Online (Sandbox Code Playgroud)

大多数时候你想使用const char*.

改变变量的类型:

您无法更改变量的类型,但可以将变量的地址重新解释为另一种类型.要做到这一点,你使用铸造.


siu*_*nin 8

我不知道如何在C++中改变变量的数据类型...

'const'是你对编译器做出的关于不修改值的承诺.当你不这样做时它会抱怨(可能在这个过程中发现了z bug).它还有助于它进行各种优化.

以下是一些常见示例及其含义:

f ( const int a  )
Run Code Online (Sandbox Code Playgroud)

f不能改变'a'的值.

f ( int const a )
Run Code Online (Sandbox Code Playgroud)

相同,但以奇怪的方式写

f ( const int const a )
Run Code Online (Sandbox Code Playgroud)

什么都没有,gcc告诉我"重复const"

f ( const int * pa )
Run Code Online (Sandbox Code Playgroud)

f不能改变pa指向的值

f ( int * const pa )
Run Code Online (Sandbox Code Playgroud)

f不能改变指针的值

f ( const int * const pa )
Run Code Online (Sandbox Code Playgroud)

f不能改变指针的值,也不能改变指向的值

f ( int a ) const 
Run Code Online (Sandbox Code Playgroud)

成员函数f无法修改其对象

希望它让事情更清楚..