// ============================================================================ // p1c04_04_04 — 4.4.2.4 const修饰对象(常对象) // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; // --- 原文片段 [58954456:3] 4.4.2.4 const修饰对象(常对象) --- class Person{ public: Person(){ this->mAge = 0; this->mID = 0; } void ChangePerson() const{ //mAge = 100; // 非法:const 成员函数内不能修改非 mutable 成员 mID = 100; // 合法:mID 被 mutable 修饰,const 函数内可改 } void ShowPerson(){ this->mAge = 1000; cout << "ID:" << this->mID << " Age:" << this->mAge << endl; } public: int mAge; mutable int mID; }; void test(){ const Person person; //1. 可访问数据成员 cout << "Age:" << person.mAge << endl; //person.mAge = 300; //不可修改 person.mID = 1001; //但是可以修改mutable修饰的成员变量 //2. 只能访问const修饰的函数 //person.ShowPerson(); person.ChangePerson(); } // --- main --- int main() { test(); return 0; }