#include <iostream> using namespace std; class Base{ public: Base(void):m_i(0){} Base(int i):m_i(i){} int m_i; }; class Derived:public Base{ public: Derived(void):m_i(0){} Derived(int i,int j):Base(i),m_i(j){} Derived(const Derived& that): m_i(that.m_i),Base(that){} Derived& operator=(const Derived& that){ if(&that != this){ m_i = that.m_i; Base::operator=(that); //基类Base看似没有Base& operator=(const Base& that) //这个赋值拷贝函数,但是系统会为其添加一个 } } int m_i;//覆盖了基类Base总的成员变量m_i. }; int main(void){ Derived d1(100,200); Derived d2(d1); //通过这样来访问基类中的同名成员变量. cout << d1.Base::m_i << ‘ ‘ <<d1.m_i << endl;//100,200 cout << d2.Base::m_i << ‘ ‘ <<d2.m_i << endl;//100,200 Derived d3; d3 = d1; cout << d3.Base::m_i << ‘ ‘ <<d3.m_i << endl;//100,200 }
时间: 2024-10-31 03:05:00