繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM