【正文】
// Not OK。 6. const char* quote()。 public: X(int ii)。 } ///:~ Const數(shù)據(jù)成員 構造函數(shù)初始化列表: 常量數(shù)據(jù)成員必須被初始化 1. 每個對象的 const成員經(jīng)初始化后都不能改變。 // Not OK u(ip)。 to 39。 }。d。 cout c2。 const int i[] = { 1, 2, 3, 4 }。 ? 因此: 總是占用存儲; 名字是全局的。 // error!! Why?? 在編譯時,編譯器并不知道 const的值,它只是一個“ 運行時常量 ” 。 const S s[] = { { 1, 2 }, { 3, 4 } }。 int * const w = amp。 // legal but bad practice int main() {} ///:~ ? 注意 《面向對象程序設計》 中國科學技術大學計算機系 馬建輝 13 const的應用: const參數(shù) 1. 傳遞 const值 void f1(const int i) { i++。 // 按值返回 const。 // OK copies value int* ip2 = cip。 // OK //! *w() = 1。 int array2[SIZE2]。 } int X::f(){ … 。 14. } 15. const char* Quoter::quote() { 16. static const char* quotes[] = { 17. Are we having fun yet?, 18. Doctors always know best, 《面向對象程序設計》 中國科學技術大學計算機系 馬建輝 29 19. Is it ... Atomic?, 20. Fear is obscene, 21. There is no scientific evidence 22. to support the idea 23. that life is serious, 24. Things that make us happy, make us wise, 25. }。 ?const為程序設計提供了又一種非常好的類型檢查形式及安全性。 30. return quotes[lastquote = qnum]。 // OK } 《面向對象程序設計》 中國科學技術大學計算機系 馬建輝 27 const對象與 const成員函數(shù) ? 聲明為 const的對象是不能被賦值的 ? 聲明為 const的對象不能隨便調用任意的成員函數(shù) ()。 //const對象 《面向對象程序設計》 中國科學技術大學計算機系 馬建輝 25 如何保證 const對象不被改變? ?公有數(shù)據(jù):只要用戶不去改變,這些數(shù)據(jù)保持不變是很容易實現(xiàn)的。 void print()。x。 //可能會有 Warning,跟編譯選項有關 f6() = X(1)。 // But this works fine too! } ///:~ 對內部類型來說,按值返回 const量并沒有什么特別的意義 。d。 int main() { cout type a character amp。(因此,不用擔心名字沖突) ? 當定義一個 const時,必須賦一個值給它,除非用 extern做出了清楚的說明?!睹嫦驅ο蟪绦蛟O計》 中國科學技術大學計算機系 馬建輝 1 第六章 類成員 (二