.Declare a variable(常数) to have a constant value.
.Compile time constants.
.const int bufsize = 1024;
.value must be initialized
.unless you make an explicit extern declaration .
.extern const int bufsize;
.compiler won’t let you change it.
.Compile time constants are entries in compiler symbol table, not really variables.
.数组元素的个数在编译时必须是已知的
.例:
const int class_size = 12; //Be Known in compile time
int finalGrade[class_size]; //OK
int x;
cin >> x;
const int class_size = x; //OK
double class_Array[class_Array]; //Error! Be known in runing!
.const object [const 对象]
.例:const Currency the_raise(42, 38); 这样会导致整个类的成员都不能被
访问,所以可以在成员函数后面加上const进行说明
.const member function useage
.Repeat the const keyword int the definition as well as the declaration
.例如:
int get_day() const;
int get_day() const { ... }
.Function members that do not modify data should be declared const
.const member functions are safe for const const objects-实际上说的是"this"
为 const [1-1.cpp]
#include <iostream>
using namespace std;
class A{
public:
A() : i(0) { }
//overload
void f() { cout << "A::f()" << endl; } //void f(A* this) { ... }
void f() const { cout << "A::f() const" << endl; } //void f(const A* this) { ... }
void set(int ii) { i = ii; }
private:
int i;
};
int main()
{
const A a; //There 'i' must be initialized
a.f();
A aa;
aa.f();
aa.set(1);
return 0;
}
.Constant in class [成员变量为const]- [1-2.cpp]
class A{
const int i;
};
//.member variable must be initialized in initializer list of the constructor.
.Compile-time constant in classes
class A{
const int size;
int array[size]; //Error!
...
};
||
||
class A{
static const int size = 100;
int array[size];
...
};
or
class A{
enum { size = 100; };
int array[size];
...
};
[1-2.cpp]
#include <iostream>
using namespace std;
class A{
public:
A() : i(0) { }
void f() { }
private:
const int i; //'i' must be initialized
};
int main()
{
A a;
return 0;
}