// ============================================================================ // p1c04_07_06 — 4.7.3 继承中同名成员的处理方法 // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; // --- 原文片段 [58954461:5] 4.7.3 继承中同名成员的处理方法 --- class Base{ public: Base():mParam(0){} void Print(){ cout << mParam << endl; } public: int mParam; }; class Derived : public Base{ public: Derived():mParam(10){} void Print(){ //在派生类中使用和基类的同名成员,显示使用类名限定符 cout << Base::mParam << endl; cout << mParam << endl; } //返回基类重名成员 int& getBaseParam(){ return Base::mParam; } public: int mParam; }; int main(){ Derived derived; //派生类和基类成员属性重名,子类访问成员默认是子类成员 cout << derived.mParam << endl; //10 derived.Print(); //类外如何获得基类重名成员属性 derived.getBaseParam() = 100; cout << "Base:mParam:" << derived.getBaseParam() << endl; return EXIT_SUCCESS; } // --- main ---