The first motivation for const seems to have been to eliminate the use of preprocessor #define for value substitution. It has since been put to use for pointers, function arguments, return types, class objects and member functions.        (Page 334)

1 Value substitution        (Page 334)

Because the preprocessor simply does text replacement and has no concept nor facility for type checking.

const in header files          (Page 335)

A const in C++ defaults to internal linkage; that is, it is visible only whthin the file where it is defined and cannot be seen at link time by other translation units. You must always assign a initial value to a const when you define it(but const member variable in class should not assign value when it is defined), except when you make an explicit declaration using extern.

Normally, the C++ compiler avoids creating storage for a const, but instead holds the definition in its symbol table. When you use extern with const, however, you force storage to be allocated(this is also true for certain other cases, such as taking the address of a const).

2 Safety consts          (Page 336)

If you initialize a variable with a value that is produced at runtime and you know it not change for the lifetime of that variable, it is good programming practice to make it a const so the compiler will give you an error message if you accidentally try to change it.

3 Differences with C         (Page 338)

In C, a const always occupies srotage and its name is global. The C compiler cannot treat a const as a compile-time constant.

In C, if you say

const int bufsize = 100;

char buf[bufsize];

you will get an error. But is OK in C++.

C defaults to external linkage for const and it always occupies srotage. So it can not contain in header file.

4 Const pointers          (Page 340)

When using const with pointers, you have two options: const can be applied to what the pointer is pointing to, or the const can be applied to the address stored in the pointer itself.

pointer to const

const int * u;      (normal)

int const * u;      (rare)

const pointer

int d = 1;

int * const u = &d;

assignment and type checking          (Page 343)

C++ is very particular about type checking, and this extends to pointer assignments. You can assign the address of a non-const object to a const pointer because you're simply promising not to change something that is OK to change. However, you cannot assign the address of a const object to a non-const pointer because then you are saying you might change the object via the pointer.

character array literals              (Page 343)

character array literals are actually constant character arrays. If you try to change the values in a chraacter array literal, the behavior is undefined.

char * cp = "howdy";

the compiler does not allocate storage for cp;

change what pointer cp points at is undifined. If you want to be able to modify the string, put it in an array:

char cp[] = "howdy";

the compiler has allocate storage for cp.

5 Function arguments & return values

6 Classes

const member variables, const class object, const member function

const member variables

Inside a class, const partially reverts to its meaning in C. It allocates storage within each object and represents a value that is initialized once and then cannot change. The use of const inside a class means "This is constant for the lifetime of the object". However, we may wish that each different object contain a different value for that constant.

Thus, when you create an ordinary (non-static) const inside a class, you cannot give it an initial value. This initialization must occur in the constructor initializer list.

for example,

class Fred{

  const int size;

public:

  Fred(int sz);

};

Fred::Fred(int sz):size(sz){}

void main()

{

  Fred a(1);

}

Compile-time constants in classes

static const variable means "there is only one instance, regardless of how many objects of the class are created," which is precisely what we need here: a member of a class which is constant, and which cannot change from one object of the class to another. Thus a static const of a built-in type can be treated as a compile-time constant.

you must provide the initializer at the point of definition of the static const. As a constract, all other data member in class must be initialized in the constructor or in other member functions.

const object & const member functions

A const member function cannot modify any member variables.

A const object is defined the same for  a user-defined type as a built-in type. And it can only call const member function.

for example,

class X{

  int i;

public:

  X(int ii);

  int f() const;

  int modify();

};

X::X(int ii):i(ii){};

X::f() const {return i;}      // the const member function can not modify data.

X::modify() { i++;}

void main()

{

  X x1(10);

  const X x2(20);

  x1.f();       // OK

  x2.f();       // OK

  x2.modify();    // error

}

Neither constructors nor destructors can be const member functions because they virtually always perform some modification on the object during initialization and cleanup.

6 volatile

it means "This data may change outside the knowledge of the compiler."

Constants in C++的更多相关文章

  1. some OpenGL constants

    some OpenGL constants This is from (https://github.com/peterderivaz/pyopengles/blob/master/gl2.py) G ...

  2. CLR via C# 3rd - 07 - Constants and Fields

    1. Constants        A constant is a symbol that has a never-changing value. When defining a constant ...

  3. JavaScript Patterns 5.7 Object Constants

    Principle Make variables shouldn't be changed stand out using all caps. Add constants as static prop ...

  4. 深入浅出OOP(五): C#访问修饰符(Public/Private/Protected/Internal/Sealed/Constants)

    访问修饰符(或者叫访问控制符)是面向对象语言的特性之一,用于对类.类成员函数.类成员变量进行访问控制.同时,访问控制符也是语法保留关键字,用于封装组件. Public, Private, Protec ...

  5. Effective Java 30 Use Enums instead of int constants

    Enumerated type is a type whose legal values consist of a fixed set of constants, such as the season ...

  6. Task Scheduler Error and Success Constants (Windows)

    If an error occurs, the Task Scheduler APIs can return one of the following error codes as an HRESUL ...

  7. WM (Constants)

    Create page WM (Constants)   Summary WM_* Constants and their definitions or descriptions and what c ...

  8. 7.Constants and Fields

    1.Constants is a symbol that has a never-changing value.  its value must be determinable at compile ...

  9. TYPES、DATA、TYPE、LIKE、CONSTANTS、STATICS、TABLES

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  10. esriSRGeoCS3Type Constants

    ArcGIS Developer Help  (Geometry)     esriSRGeoCS3Type Constants More available geographic coordinat ...

随机推荐

  1. Codeforces Round #311 (Div. 2) D - Vitaly and Cycle(二分图染色应用)

    http://www.cnblogs.com/wenruo/p/4959509.html 给一个图(不一定是连通图,无重边和自环),求练成一个长度为奇数的环最小需要加几条边,和加最少边的方案数. 很容 ...

  2. mongodb集成spring

    1:首先需要下载mongodb的java驱动包 https://github.com/mongodb/mongo-java-driver/downloads 2:需要下载spring集成mongodb ...

  3. 【Mysql学习笔记】浅析mysql的binlog

    最近读一份关于“数据库事务故障恢复"的技术资料,发现对mysql的binlog的认识不够清楚,查阅mysql reference manual有所收获,作为笔记,记录于此. 1. What' ...

  4. Excel引用

    Excel引用 1.绝对引用  相对引用 A:A   左右拉的话会自动变为  B:B,C:C等等 $A:$A  左右拉的话仍然是A列 A$1:A1  上下拉的话,会变成A$1:A2,A$1:A3等等

  5. 对css中的浮动属性float刨根解牛

    1.浮动的框可以向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止. 脱离常规流,由于浮动框不在文档的普通流中,所以文档的普通流中的块框表现得就像浮动框不存在一样. 2.几张图说明浮动常 ...

  6. Node.js初级

    package.json文件字段说明 name:包名.包名是唯一的,只能包含小写字母.数字和下划线. version:包版本号. description:包说明. keywords:关键字数组.用于搜 ...

  7. G++ 教程(转)

    简介      gcc and g++分别是GNU的c & c++编译器 gcc/g++在执行编译工作的时候,总共需要4步  1.预处理,生成.i的文件[预处理器cpp]  2.将预处理后的文 ...

  8. setvbuf

    函数名: setvbuf 用 法: int setvbuf(FILE *stream, char *buf, int type, unsigned size); type : 期望缓冲区的类型: _I ...

  9. Java实现希尔排序(增量递减排序)

    package Insert.sort; import java.util.Scanner; /*又叫缩小增量排序,本质是插入排序,将待排的序列增量分成几个子序列,分别对每个子序列进行直接插入排序 * ...

  10. 2016iweb峰会参会总结

    2016年8月27日去国家会议中心参加iweb峰会. 8点半开始签到入场,8点20分排队签到的人已经排到另一个门口,人超级多啊. 9点一如既往的由h5女神娜姐开场. 上午场 基本是各公司的大佬们介绍各 ...