1. General Constants
Int const x = 2; or const int x = 2;
Of course, X is also an array, such as X [5]; int can be replaced with the class name, and X is the object name, which is usually an object at this time.
If int is replaced with char *, It is a regular pointer such as char * const X or const char * X; the commonly referenced format is const <type specifier> & <reference Name> For example: const double & X;
2. The following example describes how to use regular pointers as function parameters.
#include <iostream>using namespace std;const int N = 6;void print(const int* p, int n);int _tmain(int argc, _TCHAR* argv[]){int arrar[N];for (int i = 0;i <N;i++){cin>>arrar[i];}print(arrar,N);return 0;}void print(const int* p, int n){cout<<"{";for (int i= 0; i<N;i++){cout<<" "<<*(p+i);}cout <<"}";}
3. Common member functions
A member function that uses the const keyword for description. Common member functions are described in the following format:
<Type description> <Function Name> (<parameter table>) const;
Here, const is the type modifier after the function description. It is an integral part of the function type. Therefore, the const keyword must also be included in the function implementation part. Features of common member functions.
Consttest. h file
class R{public:R(int r1, int r2) { R1=r1; R2=r2; }void print();void print() const;private:int R1, R2;};
Consttest. cpp File
void R::print(){cout << "R1:" <<R1 << " R2:" <<R2<<endl;}void R::print() const{cout << "R1:" <<R1 << " R2:" <<R2<<endl;}
Implementation:
int _tmain(int argc, _TCHAR* argv[]){R a(5, 4);a.print();const R b(20, 52);b.print();return 0;}
4. Constant Variables
Header file consttest. h
Class A {// R is a constant int type reference, A is a constant int type variable, and B is a static constant int type variable. Public: A (int I); void print (); const Int & R; private: const int A; static const int B ;};
CPP file consttest. cpp
void A::print(){cout<<" const int &r "<< r <<endl <<"Const int a " <<a<<endl << "static const int b " << b <<endl;}const int A::b=10;A::A(int i):a(i), r(a){}
Implementation:
int _tmain(int argc, _TCHAR* argv[]){A a1(100),a2(0);a1.print();a2.print();return 0;}
Reference: http://www.cppblog.com/mzty/archive/2005/11/09/1001.html