您的位置:首页 > 编程语言 > C语言/C++

C++之 const

2015-11-07 00:00 423 查看
摘要: C++之 const

In the C, C++, and D programming languages, const is a type qualifier, a keyword applied to a data type that indicates that the data is constant (does not vary). While this can be used to declare constants, const in the C family of languages differs from similar constructs in other languages in being part of the type, and thus has complicated behavior when combined with pointers, references, composite data types, and type-checking.

const was introduced by Bjarne Stroustrup in C with Classes, the predecessor to C++, in 1981, and was originally called readonly.As to motivation, Stroustrup writes:

"It served two functions: as a way of defining a symbolic constant that obeys scope and type rules (that is, without using a macro) and as a way of deeming an object in memory immutable."

The first use, as a scoped and typed alternative to macros, was analogously fulfilled for function-like macros via the inline keyword. Constant pointers, and the * const notation, were suggested by Dennis Ritchie and so adopted.

const was then adopted in C as part of standardization, and appears in C89 (and subsequent versions) along with the other type qualifier, volatile. A further qualifier, noalias, was suggested at the December 1987 meeting of the X3J11 committee, but was rejected; its goal was ultimately fulfilled by the restrict keyword in C99. Ritchie was not very supportive of these additions, arguing that they did not "carry their weight", but ultimately did not argue for their removal from the standard.

D subsequently inherited const from C++, where it is known as a type constructor (not type qualifier) and added two further type constructors, immutable and inout, to handle related use cases.

#include <iostream>
#include <stdlib.h>
using namespace std;

void fun(const int &a, const int &b);
int main(void)
{
int x = 3;
int y = 5;

fun(x, y);
cout << x << "," << y << endl;
system("pause");
return 0;

}
void fun(const int &a, const int &b)
{
a = 10;
b = 20;

}

以上的程序之所以运行时报错,就是因为const关键字的限定,使得函数的形参无法改变实参的原来的值,从而在其他的程序设计中避免了误操作的发生。在本例中a,b的值无法发生改变,程序报错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++之 const