<摘自C++Primer>
const
修飾變數,則該變數初始化的時候被賦值,在程式運行過程中不能被修改
非const變數預設為extern,要使const變數能夠在其他的檔案中訪問,必須顯式地指定它為extern.
const 引用是指向const對象的引用,並且只能引用該對象的值,而不能改變它的值
<摘自孫鑫VC++深入詳解>
const char * 和char * const
很多和檔案操作相關的函數其參數類型都是const char*(指向常量的指標)與指標常量(char * const)這兩種類型。
const 在*前:表示指向常量的指標,該指標不能修改其指向的記憶體中的內容,但可以修改其所指向的記憶體位址
如 char ch[5]="lisi";
const char * pStr=ch
*pStr='w' //error
pStr="wangwu"//ok
char * const : const在*的後面表指標常量,對於指標常量必須在其定義的同事賦值。指標常量表示指標本身是常量。
char *const pStr=ch;
pStr="zhangsan"//error
*pStR='W'//OK
<摘自徐惠民C++>
常成員函數
文法格式:
傳回值類型說明符 函數名(參數表)const
特點:const是函數類型的一個組成部分,在函數定義,聲明,實現時也要帶const關鍵字。
常成員函數不能更新對象的資料成員,也不能調用該類中的非常成員函數
常對象只能調用常成員函數,但是常成員函數也可以被普通對象調用
const 關鍵字可以被用於參與對重載函數的區分
《摘自C++Reference》
include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int end;
int myints[]={10,20,30,40};
int *p;
p=find(myints,myints+4,30);
p++;
cout<<"The element following 30 is"<<*p<<endl;
vector<int> myvector(myints,myints+4);
vector<int>::iterator it;
it=find(myvector.begin(),myvector.end(),30);
it++;
cout<<"The element following 30 is"<<*it<<endl;
cin>>end;
return 0;
}
此段代碼錶明iterator和指標的關係,數組與對應類別vector的關係
建構函式初始化式:只能在建構函式定義而非聲明中指定,沒有預設建構函式的類類型成員,以及const或參考型別的成員,不管是那種類型,都必須在建構函式初始化列表中進行初始化。成員在建構函式初始化列表中被初始化的次序是定義 成員的次序。
vector通過下標不能對其賦值,只能通過push_back(),但是map以及二維vector即包含vector的vector可以通過下標來賦值。
如下代碼是合法的
vector<vector<int>> myintegers;
myintegers.resize(3);
for(int i=0;i<3;i++)
{
myintegers[i].resize(4);
}
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
myintegers[i][j]=numeric_limits<int>::min();
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
cout<< myintegers[i][j];
}
cout<<endl;
}