介紹
常成員是什么 1.常成員關鍵詞為:const 2.常成員有:常成員變量、常成員函數、常成員對象
常成員有什么用 1.常成員變量:用于在程序中定義不可修改內部成員變量的函數 2.常成員函數:只能夠訪問成員變量,不可以修改成員變量 (PS:凡是 mutable 修飾的成員變量,依然能夠修改該成員變量) 3.常成員對象:只能調用它的常成員函數,而不能調用該對象的普通成員函數(PS:只能調用常函數)
常成員變量怎么用 (1).常成員變量必須賦值,且初始化后不能更改 (2).常成員變量賦值初始化: ?1.要么聲明時賦值 ?2.要么初始化表時進行賦值 常成員函數怎么用 (1).函數體前加上 const ,例子:const int foo(){}
修飾 函數本身; (PS:只能夠訪問成員變量,不可以修改成員變量) (2).函數體后 大括號前加上 const,例子: int foo()const{}
修飾 this指針; (PS:凡是 this 指向的成員變量都不可以修改,只能訪問) 常成員對象怎么用 (1).常對象只能調用常函數 (2).被 const 修飾的對象,對象指針 or 對象引用,統稱為“常對象”
源碼
# include <iostream>
# include <string> using namespace std; class Socre
{
public : Socre ( int c) : Sum_socre ( c) , S_sumber ( c) { } ~ Socre ( ) { } void foo ( ) { cout << "正常函數" << endl; } void foo ( ) const { cout << "常函數" << endl; } void Sfoo ( int b) const { b = 30 ; cout << "const Sum_socre = " << this -> Sum_socre << endl; cout << "mutable S_sumber = " << ++ this -> S_sumber << endl; cout << "b = " << b << endl; }
private : const int Sum_socre; mutable int S_sumber;
} ; int main ( )
{ cout << "-------------正常對象版本-------------" << endl; Socre sumber ( 50 ) ; sumber. Sfoo ( 100 ) ; sumber. Sfoo ( 80 ) ; sumber. Sfoo ( 60 ) ; sumber. foo ( ) ; cout << "-------------常對象版本-------------" << endl; const Socre sumber2 ( 50 ) ; sumber2. Sfoo ( 90 ) ; sumber2. Sfoo ( 100 ) ; sumber2. Sfoo ( 700 ) ; sumber2. foo ( ) ; system ( "pause" ) ; return 0 ;
}
運行結果
-- -- -- -- -- -- - 正常對象版本-- -- -- -- -- -- -
const Sum_socre = 50
mutable S_sumber = 51
b = 30
const Sum_socre = 50
mutable S_sumber = 52
b = 30
const Sum_socre = 50
mutable S_sumber = 53
b = 30
正常函數
-- -- -- -- -- -- - 常對象版本-- -- -- -- -- -- -
const Sum_socre = 50
mutable S_sumber = 51
b = 30
const Sum_socre = 50
mutable S_sumber = 52
b = 30
const Sum_socre = 50
mutable S_sumber = 53
b = 30
常函數
請按任意鍵繼續. . .
筆記擴充
new 存儲示意圖:
源碼
# include <iostream>
# include <string> using namespace std; class A
{
public : A ( ) { cout << "A構造" << endl; } ~ A ( ) { cout << "A析構" << endl; } } ; int main ( )
{ A * pa = new A[ 3 ] ; cout << * ( ( int * ) pa- 1 ) << endl; delete [ ] pa; system ( "pause" ) ; return 0 ;
}