const對象 const(一):(轉(zhuǎn))一個(gè)函數(shù)名后面加const表示什么意思?
const(一):(轉(zhuǎn))一個(gè)函數(shù)名后面加const表示什么意思?這是將整個(gè)函數(shù)修改為const,這意味著“不能對函數(shù)體中的成員數(shù)據(jù)進(jìn)行任何更改”。如果聲明此類的const實(shí)例,則它只能調(diào)用用const
const(一):(轉(zhuǎn))一個(gè)函數(shù)名后面加const表示什么意思?
這是將整個(gè)函數(shù)修改為const,這意味著“不能對函數(shù)體中的成員數(shù)據(jù)進(jìn)行任何更改”。如果聲明此類的const實(shí)例,則它只能調(diào)用用const修飾的函數(shù)。例如:<pret t=“code”L=“CPP”> class text{public:void printcont(void)const{cout<“Hello”<<endl}void print(void){cout<<“Hello”<<endl}private:int k}const text A//常量對象int main(void){A.printcont()//OK A.print()//上面定義了類text的錯(cuò)誤//上面的a.print()調(diào)用是非法的。return 0}const對象只能調(diào)用const成員函數(shù)。無法修改const對象的值。在const member函數(shù)中修改const對象的數(shù)據(jù)成員的值是一個(gè)語法錯(cuò)誤。在常量函數(shù)中調(diào)用非常量成員函數(shù)是一個(gè)語法錯(cuò)誤。